Created
April 12, 2019 11:26
-
-
Save troelskn/a418de7ee3f0a4e8aa862aa3043d351f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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