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
I put together a diff that adds the method and some entry-level tests: Comparing rails:master...kivikakk:only · rails/rails · GitHub
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.