Django ORM’s QuerySet has a get() method, which asserts that the query only matches a single row. For some reason I thought find_by did that in Rails, too, but recent poking around led me to realise that’s not the case and I might’ve relied upon this somewhere
The basic usage looks like this (adapted from an actual use case):
Product.where(price: price, annual: true).only!
Would the core team be interested in accepting a PR for this?
It fills the niche where, for whatever reason, adding a validation or constraint that covers the exact circumstances the query is expressing is clunky or untenable, and helps express intention at the point of use that there should be only one matching row.
if you want Rails so raise an ActiveRecord::RecordNotFound error.
It seems like your .only method is just duplicating this behavior. I just wanted to mention that in case you didn’t know. But don’t let this discourage you from issuing a pull request, I am not writing on behalf of the core team, of course.
This seems to be a different use case than fetching a single record. The @kivikakk is proposing a finder method which returns the first and only record satisfying the query conditions, and raises an error in the cases where there is no matching record or (more interestingly) multiple matching records.
This seems like it would be useful, IMO. In fact, I can think of several places in our codebase at work where this might prove useful.
I think there might be some confusion; find_by already returns one record or nil. Your examples would make more sense as where(…).first, which is essentially what find_by does.
Per @Anthony_Hernandez’s comment, I’d like to assert that there is exactly one record, whereas find_by doesn’t care if there are multiple matches.
I do rather like your choice of name – wow, that was a while ago. I’ve since realised we already have a Relation#only, with a different meaning, which doesn’t seem worth moving unless upstream were to adopt that method name.