Chaining Named Scopes not working as intended
Asked Answered
G

1

3

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

Gasconade answered 10/6, 2010 at 17:43 Comment(0)
P
5

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
Pushcart answered 10/6, 2010 at 18:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.