method

default_scope

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

3Notes

If you want to do a find without the default scope...

Ramon · Jun 11, 20094 thanks

Checkout with_exclusive_scope

default_scope on create

squil · Feb 26, 20103 thanks

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

tinogomes · Mar 26, 20121 thank

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 }