Rails 3.1.3 unscoped scope
Asked Answered
S

2

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?

Score answered 4/1, 2012 at 21:59 Comment(7)
Kind of similar to #6919807Vitreous
(if you read the comments there, there's not really a solution)Vitreous
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.Vitreous
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.Pentheas
@DylanMarkow - did you have the default_scope set to where(:is_active => true)?Score
it's not working for me... what version of ruby?Score
@DylanMarkow are you defining your scope before or after default_scope?Score
S
6

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

Score answered 6/1, 2012 at 19:44 Comment(1)
As a work around, you can create a class method that uses unscoped and that works fine.Grantham
I
0

Try this

scope :inactive, lambda { unscoped.where(:is_active => false) }
Incensory answered 4/1, 2012 at 22:9 Comment(1)
ftr, neither doesn unscoped { lambda {...} }Score

© 2022 - 2024 — McMap. All rights reserved.