mirror of https://github.com/rails/rails
Merge pull request #50352 from dustinbrownman/main
Prevent duplicate records when preloading `:has_many` association
This commit is contained in:
commit
66e5ed7fa9
|
@ -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
|
||||
|
|
|
@ -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")
|
||||
|
|
Loading…
Reference in New Issue