Sha256: 4ace6b2e1d16544f7896ae7c99a6202443146036024437d886705c63597823d0

Contents?: true

Size: 1.13 KB

Versions: 9

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

module Mongoid
  module Association

    # Used for converting foreign key values to the correct type based on the
    # types of ids that the document stores.
    #
    module Constrainable

      # Convert the supplied object to the appropriate type to set as the
      # foreign key for an association.
      #
      # @example Convert the object.
      #   constraint.convert("12345")
      #
      # @param [ Object ] object The object to convert.
      #
      # @return [ Object ] The object cast to the correct type.
      def convert_to_foreign_key(object)
        return convert_polymorphic(object) if polymorphic?
        field = relation_class.fields["_id"]
        if relation_class.using_object_ids?
          BSON::ObjectId.mongoize(object)
        elsif object.is_a?(::Array)
          object.map!{ |obj| field.mongoize(obj) }
        else
          field.mongoize(object)
        end
      end

      private

      def convert_polymorphic(object)
        if object.is_a?(Mongoid::Document)
          object._id
        else
          BSON::ObjectId.mongoize(object)
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
mongoid-7.5.4 lib/mongoid/association/constrainable.rb
mongoid-7.5.3 lib/mongoid/association/constrainable.rb
mongoid-7.5.2 lib/mongoid/association/constrainable.rb
mongoid-7.5.1 lib/mongoid/association/constrainable.rb
mongoid-7.4.3 lib/mongoid/association/constrainable.rb
mongoid-8.0.1 lib/mongoid/association/constrainable.rb
mongoid-7.5.0 lib/mongoid/association/constrainable.rb
mongoid-7.4.1 lib/mongoid/association/constrainable.rb
mongoid-7.4.0 lib/mongoid/association/constrainable.rb