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

Attempted to set the readonly attribute

Error message

Attempted to set the readonly attribute '%{name}' with the value: %{value}.

What it means

as_writable_attribute! enforces readonly fields: the document is persisted, the field is in the class's readonly_attributes, and a write was attempted. Only new records or non-readonly fields are writable.

Solutions

  1. Do not write readonly fields after the document is persisted
  2. Remove the readonly flag from the field if it must be mutable
  3. Write readonly fields only during creation
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at lib/mongoid/attributes/readonly.rb:31 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/cba666ff9e1d076b. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/attributes/readonly.rb:31

      # Are we able to write the attribute with the provided name?
      #
      # @example Can we write the attribute?
      #   model.attribute_writable?(:title)
      #
      # @param [ String | Symbol ] name The name of the field.
      #
      # @return [ true | false ] If the document is new, or if the field is not
      #   readonly.
      def attribute_writable?(name)
        new_record? || (!self.class.readonly_attributes.include?(name) && _loaded?(name))
      end

      private

      def as_writable_attribute!(name, value = :nil)
        normalized_name = database_field_name(name)
        raise Errors::ReadonlyAttribute.new(name, value) unless attribute_writable?(normalized_name)

        yield(normalized_name)
      end

      def _loaded?(name)
        __selected_fields.nil? || projected_field?(name)
      end

      def projected_field?(name)
        projected = (__selected_fields || {}).keys.select { |f| __selected_fields[f] == 1 }
        projected.empty? || projected.include?(name)
      end

      module ClassMethods
        # Defines an attribute as readonly. This will ensure that the value for
        # the attribute is only set when the document is new or we are
        # creating. In other cases, the field write will be ignored with the
        # exception of #remove_attribute and #update_attribute, where an error

View on GitHub (pinned to 0da0e23d71)