💡 TIL: Rails ActiveRecord has a .sole method
26th November 2024
I just learned about `sole` and `find_sole_by`. They ensure that only a single record is returned and will raise if there is something other than one. It’s the equivalent of:
api_keys = user.api_keys.where(key: key) if api_keys.length == 1 api_key = api_keys.first elsif api_keys.length == 0 raise "No records found!" else raise "More than one matching record found!" end
More recent articles
- pick is the single-value version of pluck in Rails - 26th November 2024
- NASA's Dragonfly probe to Saturn's Titan in 2028 - 26th November 2024