{"record":{"id":"cba666ff9e1d076b","repo":"mongodb/mongoid","slug":"attempted-to-set-the-readonly-attribute-name","errorCode":null,"errorMessage":"Attempted to set the readonly attribute '%{name}' with the value: %{value}.","messagePattern":"Attempted to set the readonly attribute '%(.+?)' with the value: %(.+?)\\.","errorType":"exception","errorClass":"Mongoid::Errors::ReadonlyAttribute","httpStatus":null,"severity":"error","filePath":"lib/mongoid/attributes/readonly.rb","lineNumber":31,"sourceCode":"\n      # Are we able to write the attribute with the provided name?\n      #\n      # @example Can we write the attribute?\n      #   model.attribute_writable?(:title)\n      #\n      # @param [ String | Symbol ] name The name of the field.\n      #\n      # @return [ true | false ] If the document is new, or if the field is not\n      #   readonly.\n      def attribute_writable?(name)\n        new_record? || (!self.class.readonly_attributes.include?(name) && _loaded?(name))\n      end\n\n      private\n\n      def as_writable_attribute!(name, value = :nil)\n        normalized_name = database_field_name(name)\n        raise Errors::ReadonlyAttribute.new(name, value) unless attribute_writable?(normalized_name)\n\n        yield(normalized_name)\n      end\n\n      def _loaded?(name)\n        __selected_fields.nil? || projected_field?(name)\n      end\n\n      def projected_field?(name)\n        projected = (__selected_fields || {}).keys.select { |f| __selected_fields[f] == 1 }\n        projected.empty? || projected.include?(name)\n      end\n\n      module ClassMethods\n        # Defines an attribute as readonly. This will ensure that the value for\n        # the attribute is only set when the document is new or we are\n        # creating. In other cases, the field write will be ignored with the\n        # exception of #remove_attribute and #update_attribute, where an error","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/mongodb/mongoid/blob/0da0e23d71adfbad31128c18e5e2c8c301c6f7c4/lib/mongoid/attributes/readonly.rb#L13-L49","documentation":"Error \"Attempted to set the readonly attribute '%{name}' with the value: %{value}.\" thrown in mongodb/mongoid.","triggerScenarios":"Thrown at lib/mongoid/attributes/readonly.rb:31 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":[],"exampleFix":null,"handlingStrategy":null,"validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"0da0e23d71adfbad31128c18e5e2c8c301c6f7c4","analyzedAt":"2026-08-23T06:25:47.656Z","schemaVersion":2},"datasetVersion":"2026-08-23T08:06:27.607Z"}