Skip to content

Instantly share code, notes, and snippets.

@edvardm
Created September 6, 2013 09:13
Show Gist options
  • Save edvardm/6461426 to your computer and use it in GitHub Desktop.
Save edvardm/6461426 to your computer and use it in GitHub Desktop.
I often need this in specs, sometimes I'd like to include this in code as well. The idea is to ensure that the query returns really only single result
module FinderExtensions
def find_uniq!(cond)
res = where(cond)
res.first.tap do |r|
raise ActiveRecord::RecordNotFound unless r
raise ActiveRecord::ActiveRecordError, "multiple records found" if res[1]
end
end
end
ActiveRecord::Base.send(:extend, FinderExtensions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment