From 76d6d8828007083faa6ccca3ad0feb7ba126ef79 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sun, 2 Nov 2014 13:53:54 -0700 Subject: [PATCH] Handle `RangeError` from casting in `find_by` and `find_by!` on Relation We should not behave differently just because a class has a default scope. --- .../lib/active_record/relation/finder_methods.rb | 4 ++++ activerecord/test/cases/finder_test.rb | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 6dd932e530..eacae73ebb 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -82,12 +82,16 @@ module ActiveRecord # Post.find_by "published_at < ?", 2.weeks.ago def find_by(*args) where(*args).take + rescue RangeError + nil end # Like find_by, except that if no record is found, raises # an ActiveRecord::RecordNotFound error. def find_by!(*args) where(*args).take! + rescue RangeError + raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range value" end # Gives a record (or N records if a parameter is supplied) without any implied diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index d1ff8516e8..dc73faa5be 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -210,6 +210,16 @@ class FinderTest < ActiveRecord::TestCase assert_nil Topic.find_by_id('9999999999999999999999999999999') end + def test_find_on_relation_with_large_number + assert_nil Topic.where('1=1').find_by(id: 9999999999999999999999999999999) + end + + def test_find_by_bang_on_relation_with_large_number + assert_raises(ActiveRecord::RecordNotFound) do + Topic.where('1=1').find_by!(id: 9999999999999999999999999999999) + end + end + def test_find_an_empty_array assert_equal [], Topic.find([]) end