I'm trying to decouple ActiveRecord queries in a model so they are reusable in different circumstances. To keep it simple, say I have a model called Product:
class Product < ActiveRecord::Base
def self.over_stocked
where('stock_count >= ?', 20)
end
def self.expensive
where('price >= ?', 100.0)
end
end
If I wanted to create a new method to find products that have too much stock AND are expensive, I could merge the two queries:
...
def self.costly_stock
# SQL => '... WHERE stock_count >= 20 AND price >= 100.0'
over_stocked.merge(expensive)
end
However how can I use these two methods to create a new query for products that are either expensive OR are over stocked? E.g:
...
def expensive_or_over_stocked
# SQL => '... WHERE stock_count >= 20 OR price >= 100.0'
...
end
Basically I'm looking for something like merge
that uses OR rather than AND. Ideally the solution would return an ActiveRecord Relation and not an Array. Obviously I could rewrite the query with where('stock_count >= ? OR price >= ?', 20, 100.0)
however that wouldn't be very DRY