views:

34

answers:

1

Is it possible to use ActiveRecord named_scopes to create one query with sql OR clauses?

When I use

Model.scope1.scope2

generated query is conjunction of these scopes.

A: 

This isn't really what named scopes were designed to do, but you could probably use them with some additional code to get what you needed.

def combine_scopes(model)
  (model.scope1 + model.scope2).uniq
end

or allow any scopes to be combined

def combine_scopes(model, scope1, scope2)
  (model.send(scope1) + model.send(scope2)).uniq
end

you could even change that to allow any number of scopes using *args

Beerlington
Your method will generate multiple SQL queries. It's easy that way ;)
samuil
Personally I wouldn't do it this way, I was just suggesting a method that used named scopes. If it was me, I would just have a single named scope that used OR in the conditions parameter. Not as flexible if you have multiple named scopes, but if performance is a consideration, you might not want the additional query.
Beerlington