Monday, August 25, 2008

NAMED_SCOPE in Ruby on Rails

The has_finder gem has been added to Rails with a different name: named_scope

For better understand let go through the following example:

class Article < ActiveRecord :: Base
named_scope :published, :conditions => {:published => true}

named_scope :containing_the_letter_c, :conditions => "author LIKE '%c%’"
end

Article.published.paginate(:page => 1)
Article.published.containing_the_letter_c.count
Article.containing_the_letter_c.find(:first)

Instead of creating a new method named published to return all published posts, I'm using a named_scope to do it for me.
But it can go even further than this. Let's look at another example of how it can be used:


named_scope :written_before, lambda { |time|
{ :conditions => ['written_on < ?', time] }
}

No comments:

Post a Comment

Contact Me for any help regarding rails/nodejs/php/mysql

Name

Email *

Message *