How to use named_scope to incrementally construct a complex query?

Posted by wbharding on Stack Overflow See other posts from Stack Overflow or by wbharding
Published on 2010-03-19T23:29:15Z Indexed on 2010/03/19 23:31 UTC
Read the original article Hit count: 230

Filed under:
|

I want to use Rails named_scope to incrementally build complex queries that are returned from external methods. I believe I can get the behavior I want with anonymous scopes like so:

def filter_turkeys
  Farm.scoped(:conditions => {:animal => 'turkey'})
end

def filter_tasty
  Farm.scoped(:conditions => {:tasty => true})
end

turkeys = filter_turkeys
is_tasty = filter_tasty
tasty_turkeys = filter_turkeys.filter_tasty

But say that I already have a named_scope that does what these anonymous scopes do, can I just use that, rather than having to declare anonymous scopes? Obviously one solution would be to pass my growing query to each of the filter methods, a la

def filter_turkey(existing_query)
  existing_query.turkey # turkey is a named_scoped that filters for turkey
end

But that feels like an un-DRY way to solve the problem.

Oh, and if you're wondering why I would want to return named_scope pieces from methods, rather than just build all the named scopes I need and concatenate them together, it's because my queries are too complex to be nicely handled with named_scopes themselves, and the queries get used in multiple places, so I don't want to manually build the same big hairy concatenation multiple times.

© Stack Overflow or respective owner

Related posts about rails

Related posts about named-scope