Skip to content

Instantly share code, notes, and snippets.

@nathanclark
Created January 24, 2011 02:26
Show Gist options
  • Save nathanclark/792719 to your computer and use it in GitHub Desktop.
Save nathanclark/792719 to your computer and use it in GitHub Desktop.
[Snippet] 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