aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/preloader
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib/active_record/associations/preloader')
-rw-r--r--activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb6
-rw-r--r--activerecord/lib/active_record/associations/preloader/through_association.rb5
2 files changed, 7 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
index e794f05340..24be279449 100644
--- a/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
+++ b/activerecord/lib/active_record/associations/preloader/has_and_belongs_to_many.rb
@@ -31,10 +31,12 @@ module ActiveRecord
private
# Once we have used the join table column (in super), we manually instantiate the
- # actual records
+ # actual records, ensuring that we don't create more than one instances of the same
+ # record
def associated_records_by_owner
+ records = {}
super.each do |owner_key, rows|
- rows.map! { |row| klass.instantiate(row) }
+ rows.map! { |row| records[row[klass.primary_key]] ||= klass.instantiate(row) }
end
end
diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb
index d630fc4c63..ad6374d09a 100644
--- a/activerecord/lib/active_record/associations/preloader/through_association.rb
+++ b/activerecord/lib/active_record/associations/preloader/through_association.rb
@@ -19,8 +19,9 @@ module ActiveRecord
source_reflection.name, options
).run
- through_records.each do |owner, owner_through_records|
- owner_through_records.map! { |r| r.send(source_reflection.name) }.flatten!
+ through_records.each do |owner, records|
+ records.map! { |r| r.send(source_reflection.name) }.flatten!
+ records.compact!
end
end