ActiveRecord STI:如何摆脱父类?默认范围

发布于 2024-12-02 04:40:25 字数 497 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤者何惧 2024-12-09 04:40:25

我深入研究了 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文