Chaining Named Scopes not working as intended

久未见 提交于 2019-12-01 07:07:52

问题


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??


回答1:


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


来源:https://stackoverflow.com/questions/3016983/chaining-named-scopes-not-working-as-intended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!