From 54f4bab12dd6754552ca43d514f25fd92540bea1 Mon Sep 17 00:00:00 2001 From: Jeremy Friesen Date: Mon, 16 May 2011 11:55:24 -0400 Subject: [PATCH] Addresses an inconsistency in the ActiveRecord::Base.method_missing handling of dynamic finder methods and the passing of the &block parameter for :find_by_attributes. --- activerecord/lib/active_record/base.rb | 2 +- .../lib/active_record/relation/finder_methods.rb | 1 + activerecord/test/cases/relations_test.rb | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index cd16b8d..ce9724f 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -1042,7 +1042,7 @@ module ActiveRecord #:nodoc: if match.finder? options = arguments.extract_options! relation = options.any? ? scoped(options) : scoped - relation.send :find_by_attributes, match, attribute_names, *arguments + relation.send :find_by_attributes, match, attribute_names, *arguments, &block elsif match.instantiator? scoped.send :find_or_instantiator_by_attributes, match, attribute_names, *arguments, &block end diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 32d1cff..2b1dadf 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -259,6 +259,7 @@ module ActiveRecord if match.bang? && result.blank? raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}" else + yield(result) if block_given? result end end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index fc9df8c..d95acdc 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -372,6 +372,15 @@ class RelationTest < ActiveRecord::TestCase assert_equal Post.find(1).last_comment, post.last_comment end + def test_dynamic_find_by_attributes_should_yield_found_object + david = authors(:david) + yielded_value = nil + Author.find_by_name(david.name) do |author| + yielded_value = author + end + assert_equal david, yielded_value + end + def test_dynamic_find_by_attributes david = authors(:david) author = Author.preload(:taggings).find_by_id(david.id) -- 1.7.4.1