Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created April 12, 2019 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/a418de7ee3f0a4e8aa862aa3043d351f to your computer and use it in GitHub Desktop.
Save troelskn/a418de7ee3f0a4e8aa862aa3043d351f to your computer and use it in GitHub Desktop.
# 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