Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# frozen_string_literal: true
require "active_record"
module JustAndExactly
module ActiveRecordExtensions
MultipleRecordsFound = Class.new(ActiveRecord::ActiveRecordError)
# Like +first!+, but will also fail if the query would match more than
# one record.
def exactly_one!
results = find_nth_with_limit(0, 2)
raise ActiveRecord::RecordNotFound, "Couldn't find #{@klass.name} with [#{arel.where_sql}]" \
if results.empty?
raise MultipleRecordsFound, "Query returned more than one result for [#{arel.where_sql}]" \
if results.size > 1
results.first
end
# Like +find+, but will fail if the query would match more than one record.
def just_one
exactly_one!
rescue ActiveRecord::RecordNotFound
nil
end
end
end
ActiveRecord::Relation.include JustAndExactly::ActiveRecordExtensions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.