Photo-1 Photo-2 Photo-3 Photo-4 Photo-5 Photo-6



Full-time web developer. Part-time smart ass.

I'm Brent Collier.

After a year and a half as an engineer on Twitter's Trust & Safety team, I'm looking for my next gig. Contact me if you know of something interesting.


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.


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)