链接命名范围未按预期工作

发布于 2024-09-05 03:28:32 字数 854 浏览 8 评论 0原文

我有 2 个简单的命名范围定义如下:

class Numbers < ActiveRecord::Base
  named_scope :even, :conditions => {:title => ['2','4','6']}
  named_scope :odd, :conditions => {:title => ['1','3','5']}
end

如果我调用 Numbers.even 我会返回 2,4,6 这是正确的 如果我调用 Numbers.odd,我会返回 1,3,5,这是正确的

当我将它们链接在一起时,如下所示: Numbers.even.odd 我会返回 1,3,5,因为这是我引用的最后一个范围。所以如果我说 Numbers.odd.even 我实际上会得到 2,4,6。

当我将它们链接在一起时,我期望得到 1,2,3,4,5,6。我尝试的另一种方法是这样的:

named_scope :even, :conditions => ["title IN (?)", ['2', '4','6']]
named_scope :odd, :conditions => ["title IN (?)", ['1', '3','5']]

但是当我将它们链接在一起时我没有得到任何结果,因为它创建的查询看起来像这样:

SELECT * FROM `numbers` 
WHERE ((title IN ('1','3','5')) AND (title IN ('2','4',6')))

“AND”子句应该更改为 OR 但我不知道如何强制这样做。这可能是 ActiveRecord 的问题吗?

I have 2 simple named scopes defined as such:

class Numbers < ActiveRecord::Base
  named_scope :even, :conditions => {:title => ['2','4','6']}
  named_scope :odd, :conditions => {:title => ['1','3','5']}
end

if I call Numbers.even I get back 2,4,6 which is correct
if I call Numbers.odd I get back 1,3,5 which is correct

When I chain them together like this: Numbers.even.odd I get back 1,3,5 because that is the last scope I reference. So if I say Numbers.odd.even I would actually get 2,4,6.

I would expect to get 1,2,3,4,5,6 when I chain them together. One other approach I tried was this:

named_scope :even, :conditions => ["title IN (?)", ['2', '4','6']]
named_scope :odd, :conditions => ["title IN (?)", ['1', '3','5']]

But I get no results when I chain them together because the query it creates looks like this:

SELECT * FROM `numbers` 
WHERE ((title IN ('1','3','5')) AND (title IN ('2','4',6')))

The 'AND' clause should be changed to OR but I have no idea how to force that. Could this be an issue with ActiveRecord??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

橙味迷妹 2024-09-12 03:28:32

这是 ActiveRecord 如何处理范围的问题。当您应用多个范围时,结果将使用 AND 连接在一起。没有使用 OR 的选项。

您需要做的是合并两个结果集:

Numbers.even.all + Numbers.odd.all

It's an issue with how ActiveRecord handles scopes. When you apply multiple scopes, the results are joined together with AND. There is no option for using OR.

What you need to do instead is combine two result sets:

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