7

I've seen a lot of posts regarding this, but none seem to solve my problem. I have a default_scope on a model like so:

default_scope where(:is_active => true).order('LOWER(table.name)');

I have other (normal) scopes, and I want to create an inactive scope using unscoped. I would like to define it as a scope, but it only works when defined as a class method:

# works
def self.inactive
  unscoped { where(:is_active => false) }
end

# none of these work
scope :inactive, unscoped { where(:is_active => false) }
scope :inactive, with_exclusive_scope { where(:is_active => true) }
scope :inactive, unscoped.where(:is_active => false)
scope :inactive, lambda { unscoped { where(:is_active => false) } }
scope :inactive, unscoped { lambda { where(:is_active => false) } }
unscoped do
  scope :inactive, where(:is_active => false)
end

Is there a way that I missed, or do I have to use a class method to define this scope?

sethvargo
  • 26,739
  • 10
  • 86
  • 156
  • Kind of similar to http://stackoverflow.com/questions/6919307/rails-3-default-scope-scope-with-overrride – Kyle Fleming Jan 04 '12 at 22:31
  • (if you read the comments there, there's not really a solution) – Kyle Fleming Jan 04 '12 at 22:31
  • I would say also look into `except` and `only` but they don't seem to negate the `default_scope` from within another scope, similar to the problem with `unscoped` and `with_exclusive_scope`. – Kyle Fleming Jan 04 '12 at 22:38
  • Maybe I'm missing something, but `scope :inactive, unscoped.where(:is_active => false)` works perfectly fine for me on a Rails 3.1.3 app. I tried it on a `User` class and calling `User.inactive` gives me only those records where `is_active` is `false`. – Dylan Markow Jan 04 '12 at 23:01
  • @DylanMarkow - did you have the `default_scope` set to `where(:is_active => true)`? – sethvargo Jan 04 '12 at 23:07
  • it's not working for me... what version of ruby? – sethvargo Jan 05 '12 at 01:50
  • @DylanMarkow are you defining your `scope` before or after `default_scope`? – sethvargo Jan 06 '12 at 01:01

2 Answers2

6

There does not seem to be a way to do this. I opened an issue on the rails repo on github...

sethvargo
  • 26,739
  • 10
  • 86
  • 156
0

Try this

scope :inactive, lambda { unscoped.where(:is_active => false) }
Marek Příhoda
  • 11,108
  • 3
  • 39
  • 53