Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: duplicate objects stored in has many association after save #42550

Merged
merged 1 commit into from Jun 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -79,7 +79,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 @@ -440,7 +440,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 @@ -454,7 +454,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 @@ -1471,6 +1471,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