💡 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
- Ruby's clamp method reduces conditionals - 24th February 2025
- Regex within string square brackets - 24th February 2025
- Elegant solution to versioning an API - 24th February 2025