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

Viewed 33727

Where I used to do this:

Foo.find_by_bar('a-value')

I can now do this:

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

Is this recommended? Is this the best way? Should I continue to use the "old" way because it continues to be useful syntactic sugar, or is there an Even Better way I can do that now, which will support chaining and all the other good stuff?

5 Answers

If you need one and only one record (which I came here looking for), Rails 7.0 introduces find_sole_by (or where(...).sole) for this.

The behaviour is as follows:

Finds the sole matching record. Raises ActiveRecord::RecordNotFound if no record is found. Raises ActiveRecord::SoleRecordExceeded if more than one record is found.

Use case is simple:

Foo.find_sole_by(bar: 'a-value')

Handy for those occasions where a single record is mandatory.

Related