Merge pull request #50352 from dustinbrownman/main

Prevent duplicate records when preloading `:has_many` association
This commit is contained in:
John Hawthorn 2023-12-13 16:04:33 -08:00 committed by GitHub
commit 66e5ed7fa9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 2 deletions

View File

@ -247,8 +247,8 @@ module ActiveRecord
association = owner.association(reflection.name)
if reflection.collection?
association.loaded!
association.target.concat(records)
not_persisted_records = association.target.reject(&:persisted?)
association.target = records + not_persisted_records
else
association.target = records.first
end

View File

@ -804,6 +804,17 @@ class PreloaderTest < ActiveRecord::TestCase
end
end
def test_preload_does_not_concatenate_duplicate_records
post = posts(:welcome)
post.reload
post.comments.create!(body: "A new comment")
ActiveRecord::Associations::Preloader.new(records: [post], associations: :comments).call
assert_equal post.comments.length, post.comments.count
assert_equal post.comments.all.to_a, post.comments
end
def test_preload_for_hmt_with_conditions
post = posts(:welcome)
_normal_category = post.categories.create!(name: "Normal")