Sam Saffron Sam Saffron - 8 months ago 22
Ruby Question

Dynamic find conditions in active record

I have an index action in rails that can handle quite a few params eg:

params[:first_name] # can be nil or first_name
params[:age] # can be nil or age
params[:country] # can be nil or country

When finding users I would like to AND all the conditions that are not nil. This gives me 8 permutations of the find conditions.

How can I can I keep my code DRY and flexible and not end up with a bunch of
statements just to build the conditions for the find. Keep in mind that if no conditions are specified I just want to return


This seems to work quite nicely:

conditions = params.slice(:first_name, :age, :country)
hash = conditions.empty? ? {} : {:conditions => conditions}
@users = User.all hash