123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Association::Referenced::HasMany::Buildable

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

Overview

The Builder behavior for has_many 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.

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 document to query for.

  • selected_fields (nil) (defaults to: nil)

    Must be nil.

Returns:

[ GitHub ]

  
# File 'lib/mongoid/association/referenced/has_many/buildable.rb', line 24

def build(base, object, type = nil, selected_fields = nil)
  return (object || []) unless query?(object)
  
  # Handle array of hashes from $lookup aggregation
  if object.is_a?(Array) && object.all? { |o| o.is_a?(Hash) }
    return object.map { |attrs| Factory.execute_from_db(klass, attrs, nil, selected_fields, execute_callbacks: false) }
  end
  
  return [] if object.is_a?(Array)
  query_criteria(object, base)
end

#query?(object) ⇒ Boolean (private)

[ GitHub ]

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

def query?(object)
  object && Array(object).all? { |d| !d.is_a?(Mongoid::Document) }
end