链接命名范围未按预期工作
我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 ActiveRecord 如何处理范围的问题。当您应用多个范围时,结果将使用 AND 连接在一起。没有使用 OR 的选项。
您需要做的是合并两个结果集:
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: