1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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.
This commit is contained in:
Sean Griffin 2014-11-02 13:53:54 -07:00
parent d5902c9e7e
commit 76d6d88280
2 changed files with 14 additions and 0 deletions

View file

@ -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 <tt>find_by</tt>, except that if no record is found, raises
# an <tt>ActiveRecord::RecordNotFound</tt> 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

View file

@ -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