Skip to main content

Posts

Showing posts from December, 2018

Nested forms in rails

Nested forms allows to generate, destroy and edit multiple models belongs to the parent. For achieving nested models we are using nested_form gem. gem "nested_form" Add to asset pipeline in application.js file //= require jquery_nested_form Run bundle install Recipe model ins has_many association with recipe_items. Nested attributes able to use as a  accepts_nested_attributes_for : recipe_items class Recipe < ApplicationRecord     has_many :recipe_items     accepts_nested_attributes_for : recipe_items end class  Recipe Item < ApplicationRecord     belongs_to :r ecipe end Change form_for to nested_form_for helper method as per the nested form documentation. <%= nested_form_for @recipe do |form| %>   <div class="field">     <%= form.label :name %>     <%= form.text_field :name, id: :recepy_name %>   </div>   <div class="field">...

Json in ruby on rails

JSON is Javascript object notation is used to storing and exchanging data between client and server. Json is easy to write and understand when comparing with XML. Know more about json visit json.org . Json Examples: {    " author ": "gaesh"    "title": "About json",    "total_posts": 20 } Json with Arrays: {    "author": "ganesh"    "title": "About json",    "total_posts": 20,    "comments": [                             {"author": "john"} ,                             {"title": "json example"}                        ...

Ruby rake commands for rails database

 Rake commands for the database. rake db:migrate - create a database rake db:drop - drop database rake db:reset - reset will drop the database, create database and migrate to database rake db:version - current version of schema file rake db:setup - create database, load all schema and initialize seed data  rake db:migrate:status - Load the status of migration file. rake g migration create_table_name - create a table name. rake g migration add_< field name >_to_< table_name > - add columns to table rake db:migrate - add to migration files to database rake db:seed - add seed data to database working with arrays in seed file rake db:rollback - rollback last migration file rake db:rollback STEP=n - rollback specific number of steps rake db:schema:cache:dump   - create a schema_cache.yml file rake db:schema:cache:clear   - removes a schema_cache.yml file

Devise concepts part #4

Timeoutable is one of the module in devise. It expires session that have not to be active in specific period of time. Add timeoutable module to devise user model. class User < ApplicationRecord   devise :database_authenticatable, :registerable,          :recoverable, :rememberable, :validatable, :timeoutable end Add timeout in devise.rb under intilizers.  config.timeout_in = 30.minutes Default session out in 30 minutes. It will ask users credentials once timeout session without an activity. Related Articles: Devise setup Add necessary fields to devise model Devise redirect hooks

Resque setup in ruby on rails

Resque is ruby library for creating and queuing background jobs with the redis-backed. Know more about resque:  https://github.com/resque/resque redis:  https://redis.io/ Install redis on ubuntu brew install redis Install linuxbrew for linux visit http://linuxbrew.sh/ Add resque gem to Gemfile gem 'resque' Run bundle install Set routes for resque to view background jobs and stats on browser. require 'resque/server' mount Resque::Server.new, at: "/resque" Set active jobs queuing adapter to resque in application.rb. config.active_job.queue_adapter = :resque Under lib/tasks create file resque.rake require 'resque/tasks' task 'resque:setup' => :environment Start redis server redis-server from terminal Find all running background jobs in development localhost:3000/resque/overview

How to use concerns in ruby on rails

Concerns are  like modules in ruby. Concerns folder found under model and controllers. Callbacks can also use with concerns. Create a next.rb under concerns. Create module in next.rb file. module Next     extend ActiveSupport::Concern     included do        def previous          Post.where(["id < ?", id]).last        end            def next          Post.where(["id > ?", id]).first        end     end     end Module next is inside the next.rb. This file used for navigate next and previous posts. Now just include the module in respective model. class Post < ApplicationRecord     include Next end   As per the discussions you can also set callbacks for corcens methods. Here, i am taking example that already written in secure random rails post. A...

HTTP APIs with HTTParty gem in ruby on rails

Install HTTparty gem. Visit github for HTTParty gem doc . url2 = 'https://jsonplaceholder.typicode.com/photos'       response = HTTParty.get(url2) Pagination: Will_paginate gem using for the pagination. Visit documentation for pagination https://github.com/mislav/will_paginate @albums = response.paginate(:page => params[:page], :per_page => 4) Display albums in view page and add pagination to the albums. <div class="digg_pagination">         <% @albums.each do |s| %>                     <div class="col-md-3">                 <%= image_tag s["thumbnailUrl"] %>                 <p><%= link_to s["title"].truncate(30) %></p>             </div>         <% end %>           ...

SMTP From address may not be blank: nil rails action mailer

This error because of the default hash in action mailer. Default hash is from address to mailers. for below mailer it don't have any default mail address. But my case, i created a application mailer is inheriting from ActionMailer::Base. class ApplicationMailer < ActionMailer::Base   default from: "xxxxxxxxx@gmail.com"   layout 'mailer' end class PostCreate < ActionMailer::Base         def user_post(user)         @user = user         @post = @user.posts.last                 mail to: @user.email, subject: "Your post created #{@post.title}"             end end Two ways solve this kind of errors: Above case replace ActionMailer::Base from the PostCreate to ApplicationMailer Add default mailer hash to PostCreate file.

How to pass parameters through action mailer

Action mailer sends thanking mail to subscribed user. Here, we see how to pass parameters through action mailer. @subscribe is an instance variable. The variable storing parameters of subscribers but, passed as strong parameters (sub_params). We passing @subscribe as an attribute to subscribe params. Attribute holding parameters likename and email. def create     @subscribe = Subscribe.new(sub_params)          if @subscribe.save       redirect_to root_path       SubscriberMailer.subscribers_mailer(@subscribe).deliver       flash[:notice] = "Thank you for subscribing. You will get monthly and weekly mails"     else       redirect_to root_path       flash[:error] = "Some thing went wrong"            end   end This step extracting parameters and adding to the subscriber mailer in below syntax. subscriber_mailer.rb ...