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

Attempted to access attribute '%{name}' on %{klass} which wa

Error message

Attempted to access attribute '%{name}' on %{klass} which was not loaded.

What it means

Error "Attempted to access attribute '%{name}' on %{klass} which was not loaded." thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/association/accessors.rb:120

      # @param [ true | false ] reload If the association is to be reloaded.
      #
      # @return [ Proxy ] The association.
      def get_relation(name, association, object, reload = false)
        field_name = database_field_name(name)

        # As per the comments under MONGOID-5034, I've decided to only raise on
        # embedded associations for a missing attribute. Rails does not raise
        # for a missing attribute on referenced associations.
        # We also don't want to raise if we're retrieving an association within
        # the codebase. This is often done when retrieving the inverse association
        # during binding or when cascading callbacks. Whenever we retrieve
        # associations within the codebase, we use without_autobuild.
        if !without_autobuild? && association.embedded? && attribute_missing?(field_name)
          # We always allow accessing the parent document of an embedded one.
          try_get_parent = association.is_a?(
            Mongoid::Association::Embedded::EmbeddedIn
          ) && field_name == association.key
          raise Mongoid::Errors::AttributeNotLoaded.new(self.class, field_name) unless try_get_parent
        end

        if !reload && (value = ivar(name)) != false
          value
        else
          _building do
            _loading do
              if object && needs_no_database_query?(object, association)
                __build__(name, object, association)
              # Check if data was loaded via $lookup aggregation
              elsif !association.embedded? && attributes.key?(name.to_s)
                # Use the pre-loaded association data from $lookup
                __build__(name, attributes[name.to_s], association)
              else
                selected_fields = _mongoid_filter_selected_fields(association.key)
                __build__(name, attributes[association.key], association, selected_fields)
              end
            end

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/association/accessors.rb:120 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/bc4add5d2f62dad1. Report an issue: GitHub.