Named Scope Utilities
Wednesday, February 17th, 2010 · 0 comments
One of (many) cool features in Rails is the named_scope method (in Rails 3.0, this is called scope!).
Article.find(
:all,
:conditions => ["published_at IS NOT ?", nil],
:limit => 5,
:order => "published_at DESC"
)
Here's a perfectly ordinary and valid use of the find method to query all records in the database with values in their published_at column with a maximum limit of 5 records.
With a named_scope, this could be:
Article.recently_published
In the model:
class Article < ActiveRecord::Base
named_scope :recently_published,
:conditions => ["published_at IS NOT ?", nil],
:limit => 5,
:order => "published_at DESC"
end
It keeps controllers looking clean and lean. In a completely hypothetical situation, a problem could arise when for instance a varying number of records need to be pulled from the database. Instead of 5, maybe 10, or 11! named_scope's could be written for all of them, but a more simple solution is to just make a utility scope.
named_scope :limit, lambda { |limit| { :limit => limit } }
With this it's possible to do things like: Article.recently_published.limit(10), Article.find(:all).limit(9) or even Article.unpublished.limit(10000). There are multitudes of ways named_scope can be used. Check out Railscasts episode #108 for more tricks.
