Sam Saffron Sam Saffron - 5 months ago 10
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
if
statements just to build the conditions for the find. Keep in mind that if no conditions are specified I just want to return
User.all

Answer

This seems to work quite nicely:

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