I’m writing simple scopes using rails 3.2.8 where i filter with by a category column in the database, for example:
scope :category_1, where(:category => 'category_1')
scope :category_2, where(:category => 'category_2')
Then when I try to fetch objects from the database using both scopes using:
Model.category_1.category_2.all
Active record instead of generating a where clause like:
WHERE category = 'category_1' AND category = 'category_2'
generates a where clause like:
WHERE category = 'category_2'
I would expect to have both conditions ANDed resulting in a blank array as response, instead i get all category_2 objects.
If instead of using scopes, you use a class method like:
def self.category_1
self.where(:category => 'category_1')
end
I get the expected result.
Now here is the question: is this the expected rails behaviour? should my conditions be replaced by the last called scoped for the attribute or should they be added in AND clauses like the rest of the scopes that add WHERE conditions?
ActiveRecord is trying to be smart because it knows that the conditions can’t possibly overlap (similar to a set of hash keys). Try wrapping the scopes in a lambda to avoid this: