From f0182d5cb9755e2a8ef933ea6b93d5e42f6d367d Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 30 Apr 2012 15:51:09 -0700 Subject: [PATCH] only yield to finder block if something is found --- .../lib/active_record/relation/finder_methods.rb | 2 +- activerecord/test/cases/base_test.rb | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 416b55f5c56f7..36ef945b6654c 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -217,7 +217,7 @@ def find_by_attributes(match, attributes, *args) 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? + yield(result) if block_given? && result result end end diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 8a4ce5e963e19..02d5320d9d8f5 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -175,6 +175,16 @@ def test_table_exists assert Topic.table_exists? end + def test_finder_block + t = Topic.first + found = nil + Topic.find_by_id(t.id) { |f| found = f } + assert_equal t, found + + bad_id = Topic.maximum(:id) + 1 + Topic.find_by_id(bad_id) { |f| raise } + end + def test_preserving_date_objects if current_adapter?(:SybaseAdapter) # Sybase ctlib does not (yet?) support the date type; use datetime instead.