Sha256: 1a24b7e30ecf67d20df6cb1ecb2dfa2d3dfd49bf929ef5837cba8c9adb7a7fff

Contents?: true

Size: 1.15 KB

Versions: 14

Compression:

Stored size: 1.15 KB

Contents

# encoding: utf-8
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 a relation.
      #
      # @example Convert the object.
      #   constraint.convert("12345")
      #
      # @param [ Object ] object The object to convert.
      #
      # @return [ Object ] The object cast to the correct type.
      #
      # @since 2.0.0.rc.7
      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

14 entries across 14 versions & 1 rubygems

Version Path
mongoid-7.0.13 lib/mongoid/association/constrainable.rb
mongoid-7.0.12 lib/mongoid/association/constrainable.rb
mongoid-7.0.11 lib/mongoid/association/constrainable.rb
mongoid-7.0.10 lib/mongoid/association/constrainable.rb
mongoid-7.0.8 lib/mongoid/association/constrainable.rb
mongoid-7.0.7 lib/mongoid/association/constrainable.rb
mongoid-7.0.6 lib/mongoid/association/constrainable.rb
mongoid-7.0.5 lib/mongoid/association/constrainable.rb
mongoid-7.0.4 lib/mongoid/association/constrainable.rb
mongoid-7.0.3 lib/mongoid/association/constrainable.rb
mongoid-7.0.2 lib/mongoid/association/constrainable.rb
mongoid-7.0.1 lib/mongoid/association/constrainable.rb
mongoid-7.0.0 lib/mongoid/association/constrainable.rb
mongoid-7.0.0.beta lib/mongoid/association/constrainable.rb