Overriding a Rails default_scope

If all you need is to change the order defined in default_scope, you can use the reorder method.

class Foo < ActiveRecord::Base
  default_scope order('created_at desc')
end

Foo.reorder('created_at asc')

runs the following SQL:

SELECT * FROM "foos" ORDER BY created_at asc

In Rails 3:

foos = Foo.unscoped.where(:baz => baz)

Since 4.1 you can use ActiveRecord::QueryMethods#unscope to fight default scope:

class User < ActiveRecord::Base
  default_scope { where tester: false }
  scope :testers, -> { unscope(:where).where tester: true }
  scope :with_testers, -> { unscope(:where).where tester: [true, false] }
  # ...
end

It is currently possible to unscope stuff like: :where, :select, :group, :order, :lock, :limit, :offset, :joins, :includes, :from, :readonly, :having.

But still please avoid using of default_scope if you can. It's for your own good.


Short answer: Do not use default_scope unless you really have to. You'll probably be better off with named scopes. With that said, you can use with_exclusive_scope to override the default scope if you need to.

Have a look at this question for more details.