Sha256: 37ad8b72694b4c6e77291953d0f123bcc441387f23f090d609d5e2c3795811e5

Contents?: true

Size: 1.42 KB

Versions: 8

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

module Mongoid
  module Association
    module Referenced
      class BelongsTo

        # The Builder behavior for belongs_to associations.
        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)
            cls = type ? type.constantize : relation_class
            crit = cls.criteria
            crit = crit.apply_scope(scope)
            crit.where(primary_key => object)
          end

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

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
mongoid-7.5.4 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.5.3 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.5.2 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.5.1 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.4.3 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.5.0 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.4.1 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.4.0 lib/mongoid/association/referenced/belongs_to/buildable.rb