From 13b3c77e393b8fb02588f39e6bfa10c832e251ff Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 30 Mar 2012 12:44:45 +0100 Subject: Add Relation#find_by and Relation#find_by! --- activerecord/lib/active_record/querying.rb | 1 + .../lib/active_record/relation/finder_methods.rb | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) (limited to 'activerecord/lib') 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 nil. + # + # Post.find_by name: 'Spartacus', rating: 4 + # Post.find_by "published_at < ?", 2.weeks.ago + # + def find_by(*args) + where(*args).first + end + + # Like find_by, except that if no record is found, raises + # an ActiveRecord::RecordNotFound error. + def find_by!(*args) + where(*args).first! + end + # A convenience wrapper for find(:first, *args). You can pass in all the # same arguments to this method as you can to find(:first). def first(*args) -- cgit v1.2.3