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

Attempted to modify the read-only association '%{name}' on '

Error message

Attempted to modify the read-only association '%{name}' on '%{klass}'.

What it means

Error "Attempted to modify the read-only association '%{name}' on '%{klass}'." thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/association/referenced/has_many_through.rb:191

            if reload || !instance_variable_defined?("@_#{assoc_name}")
              set_relation(assoc_name, HasManyThrough::Proxy.new(self, assoc))
            end
            instance_variable_get("@_#{assoc_name}")
          end
        end

        def define_through_ids_getter!
          assoc_name = name
          ids_method = :"#{assoc_name.to_s.singularize}_ids"
          @owner_class.re_define_method(ids_method) do
            send(assoc_name).pluck(:_id)
          end
        end

        def define_readonly_setter!
          assoc = self
          @owner_class.re_define_method(:"#{name}=") do |_object|
            raise Mongoid::Errors::ReadonlyAssociation.new(self.class, assoc)
          end
        end

        def default_primary_key
          PRIMARY_KEY_DEFAULT
        end
      end
    end
  end
end

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/association/referenced/has_many_through.rb:191 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/284f511f2e75fede. Report an issue: GitHub.