ActiveRecord STI: How can I break out of the parent class' default scope
Asked Answered
S

2

11

On Rails 3.1 RC6, given

class Animal < ActiveRecord::Base
  default_scope where(legs: 4)
end

The following does not work as expected:

class Man < Animal
  default_scope unscoped.where(legs: 2)
end

The resulting SQL statement looks like this:

SELECT * FROM animals WHERE legs = 4 AND legs = 2

How can I override the parent class' default scope entirely?

I've also tried the followings none of which work:

default_scope{ unscoped.where legs: 2 }
default_scope with_exclusive_scope{ legs: 2 }
Starrstarred answered 30/8, 2011 at 5:53 Comment(0)
S
10

I dug into Rails' source code and came up with a solution that works under Rails 3.1 (tested with activerecord 3.1.0.rc6):

class Animal < ActiveRecord::Base
  default_scope where(legs: 4)
end

class Man < Animal
  self.default_scopes = []
  default_scope where(legs: 2)
end
Starrstarred answered 13/3, 2012 at 8:50 Comment(1)
Seems that this works in Rails 3.0: self.default_scoping = []Rondelet
E
0

I'd found this and it helped me http://m.onkey.org/default-scopes-and-inheritance-to-the-rescue

Emmanuel answered 19/5, 2015 at 8:2 Comment(1)
This link is broken. Do you know where it might have moved to?Threesome

© 2022 - 2024 — McMap. All rights reserved.