ActiveRecord STI:如何突破父类的默认范围

时间:2011-08-30 05:53:07

标签: activerecord ruby-on-rails-3.1 sti default-scope

On Rails 3.1 RC6,给出

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

以下内容无效:

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

生成的SQL语句如下所示:

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

如何完全覆盖父类的默认范围?

我也尝试了以下所有工作:

default_scope{ unscoped.where legs: 2 }
default_scope with_exclusive_scope{ legs: 2 }

2 个答案:

答案 0 :(得分:8)

我挖掘了Rails的源代码,并提出了一个在Rails 3.1下运行的解决方案(使用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

答案 1 :(得分:0)