Thu, 14 Aug 2008
Rails 2.1.0 - named_scope
New version of rails comes with a great feature called named_scope.
# in your model.rb

class Model < ActiveRecord::Base
 has_many ...
 belongs_to ...

 named_scope :active, :conditions => {:state => 'active'}
 named_scope :today, :conditions => ['date_created between ? and ?', Time.today.to_i, Time.today.to_i+3600*24-1]
 named_scope :by_date_asc, :order => 'date_created asc'
 named_scope :by_date_desc, :order => 'date_created desc'
 named_scope :user_name, lambda {|name| {:conditions => {:username => name}}
and you can use its as:
# somewhere in your code

 @data = Model.today
 @data = Model.today.active.by_date_asc
 @data = Model.user_name('some user').active.today.by_date_desc

(posted at 23:36 | filed under programming/rails | link)    (comments | add new)