Module: Mongoid::Association::Referenced::WithPolymorphicCriteria Private

Included in:
HasMany, HasOne::Buildable
Defined in:
lib/mongoid/association/referenced/with_polymorphic_criteria.rb

Overview

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

Implements the ‘with_polymorphic_criteria` shared behavior.

Instance Method Summary collapse

Instance Method Details

#with_polymorphic_criterion(criteria, base) ⇒ Mongoid::Criteria

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.

If the receiver represents a polymorphic association, applies the polymorphic search criteria to the given ‘criteria` object.

Parameters:

  • criteria (Mongoid::Criteria)

    the criteria to append to if receiver is polymorphic.

  • base (Mongoid::Document)

    the document to use when resolving the polymorphic type keys.

Returns:

  • (Mongoid::Criteria)

    the resulting criteria, which may be the same as the input.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mongoid/association/referenced/with_polymorphic_criteria.rb', line 20

def with_polymorphic_criterion(criteria, base)
  if polymorphic?
    # 1. get the resolver for the inverse association
    resolver = klass.reflect_on_association(as).resolver

    # 2. look up the list of keys from the resolver, given base
    keys = resolver.keys_for(base)

    # 3. use equality if there is just one key, `in` if there are multiple
    if keys.many?
      criteria.where(type => { :$in => keys })
    else
      criteria.where(type => keys.first)
    end
  else
    criteria
  end
end