Class: Mongoid::Association::EagerLoad::SameDatabaseTargets Private

Inherits:
PolymorphicTargets show all
Defined in:
lib/mongoid/association/eager_load/polymorphic_targets.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Targets that live in the root's own database. A $lookup can reach them, so every type is fetched together in one $facet aggregation against the root collection.

For { 'Printer' => [ id1 ], 'Scanner' => [ id2 ] } it runs:

[
{ '$limit' => 1 },   # one input doc, so each facet branch runs once
{ '$facet' => {      # run one $lookup per type within a single query
  'Printer' => [ { '$lookup' => { 'from' => 'printers', ... } }, ... ],
  'Scanner' => [ { '$lookup' => { 'from' => 'scanners', ... } }, ... ]
} }
]

Instance Method Summary collapse

Methods inherited from PolymorphicTargets

for

Constructor Details

#initialize(association, keys_by_type, root_class) ⇒ SameDatabaseTargets

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of SameDatabaseTargets.



86
87
88
89
# File 'lib/mongoid/association/eager_load/polymorphic_targets.rb', line 86

def initialize(association, keys_by_type, root_class)
  super(association, keys_by_type)
  @root_class = root_class
end

Instance Method Details

#fetchHash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns The targets, as { type => { primary_key => document } }.

Returns:

  • (Hash)

    The targets, as { type => { primary_key => document } }.



92
93
94
95
96
97
98
99
100
# File 'lib/mongoid/association/eager_load/polymorphic_targets.rb', line 92

def fetch
  return {} if @keys_by_type.empty?

  aggregated = @root_class.collection.aggregate([ { '$limit' => 1 }, { '$facet' => facets } ]).first
  aggregated.to_h do |type, branch|
    # $limit => 1 makes each branch yield a single wrapper holding the matches.
    [ type, indexed(branch.first['matches'], model_for(type)) ]
  end
end