method
default_scope
v3.0.9 -
Show latest stable
- Class:
ActiveRecord::Base
default_scope(options = {})protected
Sets the default options for the model. The format of the options argument is the same as in find.
class Person < ActiveRecord::Base default_scope order('last_name, first_name') end
default_scope is also applied while creating/building a record. It is not applied while updating a record.
class Article < ActiveRecord::Base default_scope where(:published => true) end Article.new.published # => true Article.create.published # => true
4Notes
If you want to do a find without the default scope...
Checkout with_exclusive_scope
finding without default scopes in rails 3
if you want to find without default scopes in rails 3 and with_exclusive_scope is giving you protected method errors in controllers, use unscoped for a similar purpose
default_scope on create
If you specify +:conditions+ in your +default_scope+ in form of a Hash, they will also be applied as default values for newly created objects. Example:
class Article
default_scope :conditions => {:published => true}
end
Article.new.published? # => true
However:
class Article
default_scope :conditions => 'published = 1'
end
Article.new.published? # => false
Use exist scopes on default_scope - pay attention
To use exists scopes on default_scope , you can use something like:
class Article < ActiveRecord::Base
scope :active, proc {
where("expires_at IS NULL or expires_at > '#{Time.now}'")
}
scope :by_newest, order("created_at DESC")
default_scope by_newest
end
But, if you would add a filter, and it require a lazy evaluate, use block on default_scope declaration, like:
default_scope { active.by_newest }