Passing a hash of conditions to find in rails

Anton Jenkins | April 21, 2009

I just stumbled across a neat trick in ActiveRecord which could help make your code more readable:

1
2
3
User.find(:first, :conditions => { :forename => 'Anton',
                                   :surname => 'Jenkins',
                                   :age => some_value_from_a_form })

To me this is so much more readable than:

1
2
User.find(:first, :conditions => ["forename = ? AND surname = ? AND age = ?",
                                  'Anton', 'Jenkins', some_value_from_a_form])

I know which one I prefer. I can’t believe I’ve never seen anyone using hashes for conditions before! Have I had my head in the sand?

Let me know if there are any gotchas with this technique. Maybe there is a good reason I’ve not seen it used before.

comments powered by Disqus