Skip to content

Commit c5a8621

Browse files
authored
Merge pull request rails#50129 from MaxLap/fix_preload_concat
Fix: Preloader should no longer overwrites built records
2 parents 049c951 + 7f283f9 commit c5a8621

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

activerecord/lib/active_record/associations/preloader/association.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,8 @@ def associate_records_to_owner(owner, records)
245245
association = owner.association(reflection.name)
246246

247247
if reflection.collection?
248-
association.target = records
248+
association.loaded!
249+
association.target.concat(records)
249250
else
250251
association.target = records.first
251252
end

activerecord/test/cases/associations_test.rb

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1452,6 +1452,51 @@ def test_preloads_belongs_to_a_composite_primary_key_model_through_id_attribute
14521452
assert_match(expectation, preload_sql)
14531453
assert_equal order, loaded_order_agreement.order
14541454
end
1455+
1456+
def test_preload_keeps_built_has_many_records_no_ops
1457+
post = Post.new
1458+
comment = post.comments.build
1459+
1460+
assert_no_queries do
1461+
ActiveRecord::Associations::Preloader.new(records: [post], associations: :comments).call
1462+
1463+
assert_equal [comment], post.comments.to_a
1464+
end
1465+
end
1466+
1467+
def test_preload_keeps_built_has_many_records_after_query
1468+
post = posts(:welcome)
1469+
comment = post.comments.build
1470+
1471+
assert_queries(1) do
1472+
ActiveRecord::Associations::Preloader.new(records: [post], associations: :comments).call
1473+
1474+
assert_includes post.comments.to_a, comment
1475+
end
1476+
end
1477+
1478+
1479+
def test_preload_keeps_built_belongs_to_records_no_ops
1480+
post = Post.new
1481+
author = post.build_author
1482+
1483+
assert_no_queries do
1484+
ActiveRecord::Associations::Preloader.new(records: [post], associations: :author).call
1485+
1486+
assert_same author, post.author
1487+
end
1488+
end
1489+
1490+
def test_preload_keeps_built_belongs_to_records_after_query
1491+
post = posts(:welcome)
1492+
author = post.build_author
1493+
1494+
assert_no_queries do
1495+
ActiveRecord::Associations::Preloader.new(records: [post], associations: :author).call
1496+
1497+
assert_same author, post.author
1498+
end
1499+
end
14551500
end
14561501

14571502
class GeneratedMethodsTest < ActiveRecord::TestCase

0 commit comments

Comments
 (0)