Created
September 6, 2013 09:13
-
-
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
This file contains hidden or 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
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