Override an AR default_scope
Posted on 06/08/2011
Say you've got a Thing
class and your app uses soft deletes, so maybe you've got a default scope like so
default_scope where(:active => true)
and you want to find Thing
records that have been (soft)deleted, so you try this
Thing.where(:active => false).all
which returns this
[] #sadface
What gives?
Well, your default scope hold precedence over your where condition, so what you need to do is this
Thing.unscoped.where(:active => false).all
Using the unscoped
scope returns an AR::Relation without the default scope, allowing you query for whatever you want. Enjoy.
Update
Or, as it turns out, you can create a scope that negates the default scope, like so
class Thing
default_scope where(:active => true)
scope :inactive, where(:active => false)
end