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

Cannot set the attribute on the class.

Error message

Cannot set the %{attr} attribute on the %{klass} class.

What it means

Raised by validate_writable_field_name! when write_attribute or remove_attribute targets a declared field whose name contains a dot (.) or begins with a dollar sign ($). MongoDB forbids such keys in documents, so Mongoid blocks the write at the attribute level.

Solutions

  1. Rename the field in the model definition so it contains no dots and does not start with '$'
  2. Migrate existing documents to the new field name before removing the old one
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at lib/mongoid/fields.rb:276 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/73d07a68aa05aa2c. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/fields.rb:276

    #
    # @return [ true | false ] If this field is dotted or dollared.
    def dot_dollar_field?(name)
      n = aliased_fields[name] || name
      fields.key?(n) && (n.include?('.') || n.start_with?('$'))
    end

    # Validate whether or not the field starts with a dollar sign ($) or
    # contains a dot/period (.).
    #
    # @api private
    #
    # @raise [ InvalidDotDollarAssignment ] If contains dots or starts with a dollar.
    #
    # @param [ String ] name The field name.
    def validate_writable_field_name!(name)
      return unless dot_dollar_field?(name)

      raise Errors::InvalidDotDollarAssignment.new(self.class, name)
    end

    class << self
      # Stores the provided block to be run when the option name specified is
      # defined on a field.
      #
      # No assumptions are made about what functionality the handler might
      # perform, so it will always be called if the `option_name` key is
      # provided in the field definition -- even if it is false or nil.
      #
      # @example
      #   Mongoid::Fields.option :required do |model, field, value|
      #     model.validates_presence_of field if value
      #   end
      #
      # @param [ Symbol ] option_name the option name to match against
      # @param &block the handler to execute when the option is provided.
      def option(option_name, &block)

View on GitHub (pinned to 0da0e23d71)