ActiveRecord STI:如何摆脱父类?默认范围
在 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 }
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 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我深入研究了 Rails 的源代码,并提出了一个在 Rails 3.1 下工作的解决方案(使用 activerecord 3.1.0.rc6 进行测试):
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):
我发现了这个,它对我有帮助http://m. onkey.org/default-scopes-and-inheritance-to-the-rescue
I'd found this and it helped me http://m.onkey.org/default-scopes-and-inheritance-to-the-rescue