Skip to content

Instantly share code, notes, and snippets.

@linyiru
Created September 15, 2008 03:42
Show Gist options
  • Save linyiru/10810 to your computer and use it in GitHub Desktop.
Save linyiru/10810 to your computer and use it in GitHub Desktop.
ActiveRecord: ActiveRecord: named_scope
class User < ActiveRecord::Base
named_scope :active, :conditions => {:active => true}
named_scope :inactive, :conditions => {:active => false}
named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
end
# Standard usage
User.active # same as User.find(:all, :conditions => {:active => true})
User.inactive # same as User.find(:all, :conditions => {:active => false})
User.recent # same as User.find(:all, :conditions => ['created_at > ?', 1.week.ago])
# They're nest-able too!
User.active.recent
# same as:
# User.with_scope(:conditions => {:active => true}) do
# User.find(:all, :conditions => ['created_at > ?', 1.week.ago])
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment