Skip to content

Commit 80e240b

Browse files
committed
Fix: duplicate objects stored in has many association after save
Fixes rails#42549
1 parent 68a6952 commit 80e240b

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def ids_writer(ids)
7979
def reset
8080
super
8181
@target = []
82-
@replaced_targets = Set.new
82+
@replaced_or_added_targets = Set.new
8383
@association_ids = nil
8484
end
8585

@@ -440,7 +440,7 @@ def concat_records(records, raise = false)
440440
end
441441

442442
def replace_on_target(record, skip_callbacks, replace:, inversing: false)
443-
if replace && (!record.new_record? || @replaced_targets.include?(record))
443+
if replace && (!record.new_record? || @replaced_or_added_targets.include?(record))
444444
index = @target.index(record)
445445
end
446446

@@ -454,7 +454,7 @@ def replace_on_target(record, skip_callbacks, replace:, inversing: false)
454454

455455
yield(record) if block_given?
456456

457-
@replaced_targets << record if inversing || index
457+
@replaced_or_added_targets << record if inversing || index || record.new_record?
458458

459459
if index
460460
target[index] = record

activerecord/test/cases/associations/belongs_to_associations_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1471,6 +1471,16 @@ def test_multiple_counter_cache_with_after_create_update
14711471
end
14721472
end
14731473
end
1474+
1475+
test "assigning an association doesn't result in duplicate objects" do
1476+
post = Post.create!(title: "title", body: "body")
1477+
post.comments = [post.comments.build(body: "body")]
1478+
post.save!
1479+
1480+
assert_equal 1, post.comments.size
1481+
assert_equal 1, Comment.where(post_id: post.id).count
1482+
assert_equal post.id, Comment.last.post.id
1483+
end
14741484
end
14751485

14761486
class BelongsToWithForeignKeyTest < ActiveRecord::TestCase

0 commit comments

Comments
 (0)