123456789_123456789_123456789_123456789_123456789_

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

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

Overview

The Builder behavior for has_one associations.

Instance Method Summary

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 22

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 35

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 56

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 68

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 49

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

#with_polymorphic_criterion(criteria, base) (private)

[ GitHub ]

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

def with_polymorphic_criterion(criteria, base)
  if polymorphic?
    criteria.where(type => base.class.name)
  else
    criteria
  end
end