Chaining Named Scopes not working as intended

2020-03-26 05:24发布

问题:

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