Sha256: 1b6ad501fdb65e4809e4156a775712b9f4b06b6a50906519f92e416ea7863748

Contents?: true

Size: 1.4 KB

Versions: 14

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true
# encoding: utf-8

module Mongoid
  module Association
    module Referenced
      class BelongsTo

        # The Builder behavior for belongs_to associations.
        #
        # @since 7.0
        module Buildable

          # This method either takes an _id or an object and queries for the
          # inverse side using the id or sets the object.
          #
          # @example Build the document.
          #   relation.build(meta, attrs)
          #
          # @param [ Object ] base The base object.
          # @param [ Object ] object The object to use to build the association.
          # @param [ String ] type The type of the association.
          # @param [ nil ] selected_fields Must be nil.
          #
          # @return [ Document ] A single document.
          def build(base, object, type = nil, selected_fields = nil)
            return object unless query?(object)
            execute_query(object, type)
          end

          private

          def execute_query(object, type)
            query_criteria(object, type).limit(1).first(id_sort: :none)
          end

          def query_criteria(object, type)
            model = type ? type.constantize : relation_class
            model.where(primary_key => object)
          end

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

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
mongoid-7.3.5 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.3.4 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.2.6 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.3.3 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.3.2 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.2.5 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.2.4 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.3.1 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.3.0 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.2.3 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.2.2 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.2.1 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.2.0 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.2.0.rc1 lib/mongoid/association/referenced/belongs_to/buildable.rb