Sha256: 3a9617b7e6899ebaf7689a4b64ab3c8d6d23a4e964b92e03d72666bf89c96a6d

Contents?: true

Size: 1.28 KB

Versions: 14

Compression:

Stored size: 1.28 KB

Contents

# 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 relation.
          # @param [ String ] type The type of the relation.
          #
          # @return [ Document ] A single document.
          def build(base, object, type = 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.0.13 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.12 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.11 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.10 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.8 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.7 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.6 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.5 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.4 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.3 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.2 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.1 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.0 lib/mongoid/association/referenced/belongs_to/buildable.rb
mongoid-7.0.0.beta lib/mongoid/association/referenced/belongs_to/buildable.rb