Wednesday, 27 March 2013

To Include Pagination in application

                                    You can use will_paginate gem to include pagination.

Example :

1) Include following in your gemfile and do 'bundle install'
'gem will_paginate'

2) Use code like below in controller if say your model name is Post

 @posts = Post.where(:published => true).paginate(:page => params[:page], :per_page => 5).order('id DESC')


3) In view file use <%= will_paginate @posts %>           

Monday, 25 March 2013

Difference between .nil?, .blank? and .empty?

1) nil

In Ruby, nil in an object (a single instance of the class NilClass) so methods can be called on it. nil? is a standard method in Ruby that can be called on all objects and returns true for the nil object and false for anything else.

2) empty

 empty? is a standard Ruby method on some objects like Arrays, Hashes and Strings. Its exact behaviour will depend on the specific object, but typically it returns true if the object contains no elements.

3) blank

blank? is not a standard Ruby method but is added to all objects by Rails and returns true for nil, false, empty, or a whitespace string.

Examples :

=> true

=> false

=> false

=> false

=> false

=> false

=> true

=> false

=> true

[1, 2, 3].empty?
=> false

=> NoMethodError

=> true

=> true

=> false

Different Ways for creation of active record object

Rails Allows Programmer to create active record object using following 

1) => "David", :occupation => "Code Artist")
user = do |u| = "David"
  u.occupation = "Code Artist"
3)user = = "David"
user.occupation = "Code Artist"