Monday, February 17, 2014

Whether to Use where(...).first or find_by(...)

I was asked today whether it is better to use find_by or where(...).first in Rails and ActiveRecord.

The answer is: "it depends". find_by is less to write, but because it isn't automatically ordering by primary key in the query, which record you get back if there are two with that same field value may not be as definitive, if you are relying on the record with the lowest primary key to be returned if more than one are matched.

The ORDER BY that is automatically added by the where(...).first takes very slightly longer to process, so if it is not needed, and you don't need to do something else to the relation, find_by is probably a winner because it is shorter and faster. But to some developers, they may look at find_by and think find and that it will raise an exception if not found, which it won't, and that could cause bugs or problems diagnosing errors, so the few saved characters may not be worth it.

However, I'm starting to use find_by more than I used to.

Update: With the changes coming in Rails 4.2 (see tenderlove's post about AdequateRecord), find_by is an even better idea.

No comments: