def ensure_unique
# Ensures an Active Record query returns a *single* record, or raise exception
# Usage: MyModel.where(foo: 'bar').where(baz: 'qux).ensure_unique
if self.many?
raise ActiveRecord::RecordNotUnique, 'More than one record matched criteria. A single match was expected.'
elsif self.empty?
raise ActiveRecord::RecordNotFound, 'No matching records were found. A single match was expected.'
else
# The where method always returns a collection, even when only one record is found.
# We want to return a single item.
return self.first
end
end
def find_unique_by!(*args)
# Ensures an Active Record query returns a *single* record, or raise exception
# Usage: MyModel.find_unique_by(foo: 'bar')
result = where(*args)
if result.many?
raise ActiveRecord::RecordNotUnique, 'More than one record matched criteria. A single match was expected.'
elsif result.empty?
raise ActiveRecord::RecordNotFound, 'No matching records were found. A single match was expected.'
else
return result.first
end
end