123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Association::Referenced::HasOne::Buildable

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
Defined in: lib/mongoid/association/referenced/has_one/buildable.rb

Overview

The Builder behavior for has_one associations.

Instance Method Summary

::Mongoid::Association::Referenced::WithPolymorphicCriteria - Included

#with_polymorphic_criterion

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

Instance Method Details

#build(base, object, type = nil, selected_fields = nil) ⇒ Document

This method either takes an _id or an object and queries for the inverse side using the id or sets the object after clearing the associated object.

Parameters:

  • base (Object)

    The base object.

  • object (Object)

    The object to use to build the association.

  • type (String) (defaults to: nil)

    The type of the association.

  • selected_fields (nil) (defaults to: nil)

    Must be nil.

Returns:

[ GitHub ]

  
# File 'lib/mongoid/association/referenced/has_one/buildable.rb', line 25

def build(base, object, type = nil, selected_fields = nil)
  if query?(object)
    if !base.new_record?
      execute_query(object, base)
    end
  else
    clear_associated(object)
    object
  end
end

#clear_associated(object) (private)

[ GitHub ]

  
# File 'lib/mongoid/association/referenced/has_one/buildable.rb', line 38

def clear_associated(object)
  unless inverse
    raise Errors::InverseNotFound.new(
        @owner_class,
        name,
        object.class,
        foreign_key,
    )
  end
  if object && (associated = object.send(inverse))
    associated.substitute(nil)
  end
end

#execute_query(object, base) (private)

[ GitHub ]

  
# File 'lib/mongoid/association/referenced/has_one/buildable.rb', line 59

def execute_query(object, base)
  query_criteria(object, base).take
end

#query?(object) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/mongoid/association/referenced/has_one/buildable.rb', line 63

def query?(object)
  object && !object.is_a?(Mongoid::Document)
end

#query_criteria(object, base) (private)

[ GitHub ]

  
# File 'lib/mongoid/association/referenced/has_one/buildable.rb', line 52

def query_criteria(object, base)
  crit = klass.criteria
  crit = crit.apply_scope(scope)
  crit = crit.where(foreign_key => object)
  with_polymorphic_criterion(crit, base)
end