123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Association::EagerLoadable

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Defined in: lib/mongoid/association/eager_loadable.rb

Overview

This module defines the eager loading behavior for criteria.

Instance Attribute Summary

Instance Method Summary

Instance Attribute Details

#eager_loadable?true | false (readonly)

Indicates whether the criteria has association inclusions which should be eager loaded.

Returns:

  • (true | false)

    Whether to eager load.

[ GitHub ]

  
# File 'lib/mongoid/association/eager_loadable.rb', line 16

def eager_loadable?
  !criteria.inclusions.empty?
end

Instance Method Details

#eager_load(docs) ⇒ Array<Mongoid::Document>

Load the associations for the given documents.

Parameters:

Returns:

[ GitHub ]

  
# File 'lib/mongoid/association/eager_loadable.rb', line 25

def eager_load(docs)
  docs.tap do |d|
    if eager_loadable?
      preload(criteria.inclusions, d)
    end
  end
end

#preload(associations, docs)

Load the associations for the given documents. This will be done recursively to load the associations of the given documents’ associated documents.

Parameters:

[ GitHub ]

  
# File 'lib/mongoid/association/eager_loadable.rb', line 40

def preload(associations, docs)
  assoc_map = associations.group_by(&:inverse_class_name)
  docs_map = {}
  queue = [ klass.to_s ]

  while klass = queue.shift
    if as = assoc_map.delete(klass)
      as.each do |assoc|
        queue << assoc.class_name

        # If this class is nested in the inclusion tree, only load documents
        # for the association above it. If there is no parent association,
        # we will include documents from the documents passed to this method.
        ds = docs
        if assoc.parent_inclusions.length > 0
          ds = assoc.parent_inclusions.map{ |p| docs_map[p].to_a }.flatten
        end

        res = assoc.relation.eager_loader([assoc], ds).run

        docs_map[assoc.name] ||= [].to_set
        docs_map[assoc.name].merge(res)
      end
    end
  end
end