aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation/finder_methods.rb
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2012-03-30 12:44:45 +0100
committerJon Leighton <j@jonathanleighton.com>2012-03-30 12:52:29 +0100
commit13b3c77e393b8fb02588f39e6bfa10c832e251ff (patch)
tree01bbb86cd94d6f18060d70c8a2d7ec8bd85ed0a4 /activerecord/lib/active_record/relation/finder_methods.rb
parent3a8c54396ea3965eb7601501d7bb9618ff305728 (diff)
downloadrails-13b3c77e393b8fb02588f39e6bfa10c832e251ff.tar.gz
rails-13b3c77e393b8fb02588f39e6bfa10c832e251ff.tar.bz2
rails-13b3c77e393b8fb02588f39e6bfa10c832e251ff.zip
Add Relation#find_by and Relation#find_by!
Diffstat (limited to 'activerecord/lib/active_record/relation/finder_methods.rb')
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb19
1 files changed, 19 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 2c74f4011d..74f8e30404 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -109,6 +109,25 @@ module ActiveRecord
end
end
+ # Finds the first record matching the specified conditions. There
+ # is no implied ording so if order matters, you should specify it
+ # yourself.
+ #
+ # If no record is found, returns <tt>nil</tt>.
+ #
+ # Post.find_by name: 'Spartacus', rating: 4
+ # Post.find_by "published_at < ?", 2.weeks.ago
+ #
+ def find_by(*args)
+ where(*args).first
+ end
+
+ # Like <tt>find_by</tt>, except that if no record is found, raises
+ # an <tt>ActiveRecord::RecordNotFound</tt> error.
+ def find_by!(*args)
+ where(*args).first!
+ end
+
# A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
# same arguments to this method as you can to <tt>find(:first)</tt>.
def first(*args)