Module: Mongoid::Association::Referenced::BelongsTo::Buildable

Included in:
Mongoid::Association::Referenced::BelongsTo
Defined in:
lib/mongoid/association/referenced/belongs_to/buildable.rb

Overview

The Builder behavior for belongs_to associations.

Instance Method Summary collapse

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.

Examples:

Build the document.

relation.build(meta, attrs)

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:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/mongoid/association/referenced/belongs_to/buildable.rb', line 21

def build(_base, object, type = nil, selected_fields = nil)
  return object unless query?(object)

  # Handle array from $lookup aggregation (returns array even for belongs_to)
  if object.is_a?(Array)
    first = object.first
    case first
    when nil, Mongoid::Document then return first
    when Hash then return Factory.execute_from_db(klass, first, nil, selected_fields,
                                                  execute_callbacks: false)
    else raise ArgumentError, 'Cannot build belongs_to association from array'
    end
  end

  # Handle single hash from $lookup with $unwind
  if object.is_a?(Hash)
    return Factory.execute_from_db(klass, object, nil, selected_fields, execute_callbacks: false)
  end

  execute_query(object, type)
end