For those cases in which there can be one and only one record on the database with certain fields and I don’t just want to get the first one and silently get the wrong one. I want to make sure there’s one and only one, so, I wrote this little extension to ActiveRecord that does exactly that:
module ActiveRecordExtension extend ActiveSupport::Concern class_methods do def one_and_only records = limit(2).all.to_a if records.count > 1 raise "#{self} generated more than one record when expecting only one." else records.first end end def one_and_only! one_and_only.tap do |record| if record.nil? raise "#{self} didn't generate any records." end end end end end ActiveRecord::Base.send(:include, ActiveRecordExtension)
The first method, one_and_only, will raise an exception if there’s more than one item but it’ll return null if there aren’t any. one_and_only! will fail if there isn’t exactly one and only one record in the database.
If you don’t know why I’m calling this The Highlander query, you should go and watch Christopher Lambert’s masterpiece.