链接命名范围并不如预期 [英] Chaining Named Scopes not working as intended

查看:100
本文介绍了链接命名范围并不如预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个简单的命名范围定义为这样的:

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

如果我打电话Numbers.even我回来2,4,6这是正确的 如果我叫Numbers.odd我回来1,3,5这是正确的。

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

当我把它们连在一起就像这样:Numbers.even.odd我回去1,3,5,因为这是最后的范围,我引用。所以,如果我说Numbers.odd.even我反而得到2,4,6。

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.

我希望得到1,2,3,4,5,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')))

在'与'条款应改为OR,但我不知道如何给力的。难道这是一个问题的ActiveRecord?

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

推荐答案

这是一个问题的ActiveRecord如何处理范围。当您应用多个领域,结果与AND连接在一起。有使用或不选。

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

这篇关于链接命名范围并不如预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆