Skip to content

Commit

Permalink
MONGOID-4716 Fix eager loading of nested referenced associations #5194
Browse files Browse the repository at this point in the history
  • Loading branch information
LuginaJulia committed Jun 13, 2024
1 parent 4c4593e commit ac64fe2
Show file tree
Hide file tree
Showing 2 changed files with 1,455 additions and 7 deletions.
32 changes: 25 additions & 7 deletions lib/mongoid/association/eager_loadable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,31 @@ def eager_load(docs)
end
end

def preload(relations, docs)
relations.group_by(&:inverse_class_name)
.values
.each do |associations|
associations.group_by(&:relation)
.each do |relation, association|
relation.eager_loader(association, docs).run
# Load the associations for the given documents. This will be done
# recursively to load the associations of the given documents'
# subdocuments.
#
# @param [ Array<Association> ] association The associations to load.
# @param [ Array<Document> ] document The documents.
def preload(associations, docs)
assoc_map = associations.group_by(&:inverse_class_name)
docs_map = { klass.to_s => docs.to_set }
queue = [ klass.to_s ]

while klass = queue.shift
if as = assoc_map.delete(klass)
as.group_by(&:relation)
.each do |relation, assocs|
assocs.each { |a| queue << a.class_name }

docs = docs_map[klass] || []
res = relation.eager_loader(assocs, docs.to_a).run

res.group_by(&:class).each do |k, vs|
docs_map[k.to_s] ||= [].to_set
docs_map[k.to_s].merge(vs)
end
end
end
end
end
Expand Down
Loading

0 comments on commit ac64fe2

Please sign in to comment.