Best way to find a single record using ActiveRecord 3 / Arel? Best way to find a single record using ActiveRecord 3 / Arel? ruby ruby

Best way to find a single record using ActiveRecord 3 / Arel?


Rails 4 :

Foo.find_by bar: 'a_value' , wibble: 'a wibble value'


I think the preferable way to return a single record would be along the lines of your second example, but you can omit the limit part:

Foo.where(:bar => 'a-value').first

This follows the new syntax and supports chaining if you want to add more conditions to the lookup.


Rails gives you a whole load of magic methods for this kind of thing:

Foo.find_by_bar('a-value')

You can also use multiple attributes:

Foo.find_by_bar_and_wibble('a foo value', 'a wibble value')

And appending a ! causes it to throw a RecordNotFound if nothing's found:

Foo.find_by_bar!('a-value')