diff options
-rw-r--r-- | activerecord/lib/active_record/relation/finder_methods.rb | 7 | ||||
-rw-r--r-- | activerecord/test/cases/base_test.rb | 10 |
2 files changed, 14 insertions, 3 deletions
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 36ef945b66..1ceb1949a4 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -217,8 +217,11 @@ 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 - result + if block_given? && result + yield(result) + else + result + end end end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 02d5320d9d..da4dfb4b33 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -180,9 +180,17 @@ class BasicsTest < ActiveRecord::TestCase found = nil Topic.find_by_id(t.id) { |f| found = f } assert_equal t, found + end + def test_finder_block_nothing_found bad_id = Topic.maximum(:id) + 1 - Topic.find_by_id(bad_id) { |f| raise } + assert_nil Topic.find_by_id(bad_id) { |f| raise } + end + + def test_find_returns_block_value + t = Topic.first + x = Topic.find_by_id(t.id) { |f| "hi mom!" } + assert_equal "hi mom!", x end def test_preserving_date_objects |