Keith Schacht’s Weblog

Subscribe

💡 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

This is Rails ActiveRecord has a .sole method by Keith Schacht, posted on 26th November 2024.

Part of series Today I Learned

  1. Ruby can chain methods and right-assign - Oct. 29, 2024, 8:23 p.m.
  2. Rails migrations can include an up_only part - Oct. 29, 2024, 8:29 p.m.
  3. NASA's Dragonfly probe to Saturn's Titan in 2028 - Nov. 26, 2024, 2:58 p.m.
  4. Rails ActiveRecord has a .sole method - Nov. 26, 2024, 11:15 p.m.
  5. pick is the single-value version of pluck in Rails - Nov. 26, 2024, 11:24 p.m.

Next: pick is the single-value version of pluck in Rails

Previous: NASA's Dragonfly probe to Saturn's Titan in 2028