diff options
author | Jon Leighton <j@jonathanleighton.com> | 2012-03-30 12:44:45 +0100 |
---|---|---|
committer | Jon Leighton <j@jonathanleighton.com> | 2012-03-30 12:52:29 +0100 |
commit | 13b3c77e393b8fb02588f39e6bfa10c832e251ff (patch) | |
tree | 01bbb86cd94d6f18060d70c8a2d7ec8bd85ed0a4 /activerecord/lib/active_record | |
parent | 3a8c54396ea3965eb7601501d7bb9618ff305728 (diff) | |
download | rails-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')
-rw-r--r-- | activerecord/lib/active_record/querying.rb | 1 | ||||
-rw-r--r-- | activerecord/lib/active_record/relation/finder_methods.rb | 19 |
2 files changed, 20 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb index 0e6fecbc4b..95565b503a 100644 --- a/activerecord/lib/active_record/querying.rb +++ b/activerecord/lib/active_record/querying.rb @@ -5,6 +5,7 @@ module ActiveRecord module Querying delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped + delegate :find_by, :find_by!, :to => :scoped delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped delegate :find_each, :find_in_batches, :to => :scoped delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, 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) |