mongodb/mongoid · error · Mongoid::Errors::InvalidDiscriminatorKeyTarget

Setting the discriminator key on a child class is not allowe

Error message

Setting the discriminator key on a child class is not allowed.

What it means

Error "Setting the discriminator key on a child class is not allowed." thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/traversable.rb:135

    #
    # @returns [ Mongoid::Document ] The parent document.
    #
    # @api private
    def _parent=(document)
      @__parent = document
    end

    # Module used for prepending to the various discriminator_*= methods
    #
    # @api private
    module DiscriminatorAssignment
      # Sets the discriminator key.
      #
      # @param [ String ] value The discriminator key to set.
      #
      # @api private
      def discriminator_key=(value)
        raise Errors::InvalidDiscriminatorKeyTarget.new(self, superclass) if hereditary?

        _mongoid_clear_types

        if value
          Mongoid::Fields::Validators::Macro.validate_field_name(self, value)
          value = value.to_s
          ::Mongoid::Traversable.__redefine(self, 'discriminator_key', value)
        else
          # When discriminator key is set to nil, replace the class's definition
          # of the discriminator key reader (provided by class_attribute earlier)
          # and re-delegate to Mongoid.
          class << self
            delegate :discriminator_key, to: ::Mongoid
          end
        end

        # This condition checks if the new discriminator key would overwrite
        # an existing field.

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/traversable.rb:135 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of mongodb/mongoid@0da0e23d71 (2026-08-23). Data as JSON: /api/errors/335b56661f13b714. Report an issue: GitHub.