Skip to content

Commit

Permalink
Merge pull request #42550 from ghiculescu/belongs-to-regression
Browse files Browse the repository at this point in the history
Fix: duplicate objects stored in has many association after save
  • Loading branch information
eileencodes committed Oct 13, 2021
1 parent fb460a4 commit 9e6b1af
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
Expand Up @@ -75,7 +75,7 @@ def ids_writer(ids)
def reset
super
@target = []
@replaced_targets = Set.new
@replaced_or_added_targets = Set.new
@association_ids = nil
end

Expand Down Expand Up @@ -447,7 +447,7 @@ def concat_records(records, raise = false)
end

def replace_on_target(record, skip_callbacks, replace:, inversing: false)
if replace && (!record.new_record? || @replaced_targets.include?(record))
if replace && (!record.new_record? || @replaced_or_added_targets.include?(record))
index = @target.index(record)
end

Expand All @@ -461,7 +461,7 @@ def replace_on_target(record, skip_callbacks, replace:, inversing: false)

yield(record) if block_given?

@replaced_targets << record if inversing || index
@replaced_or_added_targets << record if inversing || index || record.new_record?

if index
target[index] = record
Expand Down
Expand Up @@ -1469,6 +1469,16 @@ def test_multiple_counter_cache_with_after_create_update
end
end
end

test "assigning an association doesn't result in duplicate objects" do
post = Post.create!(title: "title", body: "body")
post.comments = [post.comments.build(body: "body")]
post.save!

assert_equal 1, post.comments.size
assert_equal 1, Comment.where(post_id: post.id).count
assert_equal post.id, Comment.last.post.id
end
end

class BelongsToWithForeignKeyTest < ActiveRecord::TestCase
Expand Down

0 comments on commit 9e6b1af

Please sign in to comment.