Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 }
like image 537
Prathan Thananart Avatar asked Aug 30 '11 05:08

Prathan Thananart


1 Answers

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
like image 85
Prathan Thananart Avatar answered Oct 22 '22 04:10

Prathan Thananart