Module: Mongoid::Includes::Criteria

Defined in:
lib/mongoid/includes/criteria.rb

Overview

Internal: Adds and overrides methods in Mongoid::Criteria to enhance eager loading.

Instance Method Summary collapse

Instance Method Details

#includes(*relations, **options) ⇒ Object

Public: Eager loads the specified associations.

relations - The relations of the two-level relations to eager load. from: - The relation through which two-level relations are

loaded from.

from_class: - Necessary to solve ambiguity when doing two-level eager

load through a polymorphic relation.

loader: - An optional block that specifies how to load all the

related documents.

Notes:

Eager loading brings all the documents into memory, so there is a
sweet spot on the performance gains. Internal benchmarks show that
eager loading becomes slower around 100k documents, but this will
naturally depend on the specific application.

Polymorphic belongs_to relations are supported, but will trigger a
query for each collection of the matched documents types.

Example:

Album.includes(:musicians, from: :band)

Returns the cloned Mongoid::Criteria.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mongoid/includes/criteria.rb', line 38

def includes(*relations, **options)
  if options[:from]
     = add_inclusion(klass, options[:from])
    if .polymorphic_belongs_to? && !options[:from_class]
      raise Mongoid::Includes::Errors::InvalidPolymorphicIncludes.new(klass, relations, options)
    end
  end

  owner_class = options[:from_class] || .try!(:klass) || self.klass

  relations.flatten.each do |relation|
    add_inclusion(owner_class, relation, options)
  end
  clone
end

#inclusionsObject

Overrides: Get a list of criteria that are to be executed for eager loading.



11
12
13
# File 'lib/mongoid/includes/criteria.rb', line 11

def inclusions
  @inclusions ||= Mongoid::Includes::Inclusions.new
end