From fd3b6b8b8737f283ed5f42f965234c0dbc2d1c3a Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 13 Oct 2021 09:26:17 -0700 Subject: [PATCH] Merge pull request #43445 from jstncarvalho/main fix: duplicate active record objects on inverse_of --- .../active_record/associations/collection_association.rb | 4 ++++ .../test/cases/associations/inverse_associations_test.rb | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 7b29143009949..6aa213c9b0f62 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -461,6 +461,10 @@ def replace_on_target(record, skip_callbacks, replace:, inversing: false) yield(record) if block_given? + if !index && @replaced_or_added_targets.include?(record) + index = @target.index(record) + end + @replaced_or_added_targets << record if inversing || index || record.new_record? if index diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index e2c76f96f108a..4a5d56cd40416 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -721,6 +721,15 @@ def test_with_has_many_inversing_does_not_trigger_association_callbacks_on_set_w end end + def test_with_hash_many_inversing_does_not_add_duplicate_associated_objects + with_has_many_inversing(Interest) do + human = Human.new + interest = Interest.new(human: human) + human.interests << interest + assert_equal 1, human.interests.size + end + end + def test_unscope_does_not_set_inverse_when_incorrect interest = interests(:trainspotting) human = interest.human