aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorRyuta Kamizono <kamipo@gmail.com>2019-06-07 07:38:27 +0900
committerGitHub <noreply@github.com>2019-06-07 07:38:27 +0900
commite3c1f42b31b93c87188a3013a3f40cf994b7d33c (patch)
tree3087c00a6f02f477bbadd8c0a81416d66b9f05a0 /activerecord
parent1126d14c144c79745779496f39640ce066b95d1d (diff)
parent30c1999df1f50df3faa663efb90e641ff0c2d425 (diff)
downloadrails-e3c1f42b31b93c87188a3013a3f40cf994b7d33c.tar.gz
rails-e3c1f42b31b93c87188a3013a3f40cf994b7d33c.tar.bz2
rails-e3c1f42b31b93c87188a3013a3f40cf994b7d33c.zip
Merge pull request #36429 from bogdan/fix-preloading-duplicate-records
Fix preloading on AR::Relation where records are duplicated by a join
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/associations/preloader/association.rb4
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb5
2 files changed, 8 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
index 342d9e7a5a..4c7b0e6f07 100644
--- a/activerecord/lib/active_record/associations/preloader/association.rb
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -27,7 +27,9 @@ module ActiveRecord
end
def records_by_owner
- @records_by_owner ||= preloaded_records.each_with_object({}) do |record, result|
+ # owners can be duplicated when a relation has a collection association join
+ # #compare_by_identity makes such owners different hash keys
+ @records_by_owner ||= preloaded_records.each_with_object({}.compare_by_identity) do |record, result|
owners_by_key[convert_key(record[association_key_name])].each do |owner|
(result[owner] ||= []) << record
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 545bc77fed..fe7e5dc559 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -2932,6 +2932,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [], reference.ideal_jobs
end
+ def test_has_many_preloading_with_duplicate_records
+ posts = Post.joins(:comments).preload(:comments).to_a
+ assert_equal [1, 2], posts.first.comments.map(&:id)
+ end
+
private
def force_signal37_to_load_all_clients_of_firm