10

在 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 }
4

2 回答 2

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
于 2012-03-13T08:50:49.480 回答
0

我找到了这个,它帮助了我http://m.onkey.org/default-scopes-and-inheritance-to-the-rescue

于 2015-05-19T08:02:57.530 回答