From 0da4a08bdfea28a0cc881ca5831aadfcf8a3b7eb Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Sun, 5 Jun 2016 00:38:40 +0900 Subject: Prevent `RangeError` for `belongs_to` associations Currently to access `belongs_to` associations raises a `RangeError` if foreign key attribute has out of range value. It should return a nil value rather than raising a `RangeError`. Fixes #20140. --- .../lib/active_record/associations/singular_association.rb | 2 ++ .../cases/associations/belongs_to_associations_test.rb | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index e386cc0e4c..a9e7edddff 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -51,6 +51,8 @@ module ActiveRecord sc.execute(binds, klass, conn) do |record| set_inverse_instance record end.first + rescue RangeError + nil end def replace(record) diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 2418346d1b..da6e42b89b 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -1062,6 +1062,20 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal 1, parent.reload.children_count end + def test_belongs_to_with_out_of_range_value_assigning + model = Class.new(Comment) do + def self.name; "Temp"; end + validates :post, presence: true + end + + comment = model.new + comment.post_id = 10_000_000_000 + + assert_nil comment.post + assert_not comment.valid? + assert_equal [{ error: :blank }], comment.errors.details[:post] + end + def test_polymorphic_with_custom_primary_key toy = Toy.create! sponsor = Sponsor.create!(sponsorable: toy) -- cgit v1.2.3