Skip to content

Commit

Permalink
Prevent RangeError for belongs_to associations
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kamipo committed Oct 10, 2016
1 parent 88e00d3 commit 0da4a08
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ def find_target
sc.execute(binds, klass, conn) do |record|
set_inverse_instance record
end.first
rescue RangeError
nil
end

def replace(record)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1062,6 +1062,20 @@ def test_belongs_to_with_id_assigning
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)
Expand Down

0 comments on commit 0da4a08

Please sign in to comment.