Passing a hash of conditions to find in rails
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.


Recent comments
1 year 23 weeks ago
1 year 23 weeks ago
1 year 25 weeks ago
1 year 27 weeks ago
1 year 42 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 45 weeks ago
1 year 46 weeks ago
1 year 48 weeks ago