I don't think anything exists to throw an exception where there's more than one but in rails 4:
car = Car.find_by(vin: '1234567890abcdefg')
Would return the only one. The best way to enforce uniqueness is to do it on a model/db level:
class Car < ActiveRecord::Base
validates :vin, uniqueness: true
end
If, for some reason, you do need to throw an exception when there is more than one car with that vin you could write a method on the model (or monkey patch Active record):
class Car < ActiveRecord::Base
class << self
def only_one!(options)
list = where(options)
raise "Exactly one car isn't available" if list.size > 1 or list.size == 0
list.first
end
end
end
Or use a concern:
#lib/active_record_only_one.rb:
module ActiveRecordOnlyOne
extend ActiveSupport::Concern
module ClassMethods
def only_one!(options)
list = where(options)
raise "Exactly one isn't available" if list.size > 1 or list.size == 0
list.first
end
end
end
ActiveRecord::Base.send(:include, ActiveRecordOnlyOne)
.
#config/initializers/only_one.rb
require "active_record_only_one"
And then call:
Car.only_one!(vuid: "1234567890abcdefg")