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

Ambiguous associations %{candidates} defined on %{klass}.

Error message

Ambiguous associations %{candidates} defined on %{klass}.

What it means

Error "Ambiguous associations %{candidates} defined on %{klass}." thrown in mongodb/mongoid.

Source

Thrown at lib/mongoid/association/referenced/has_and_belongs_to_many.rb:257

        def create_foreign_key_field!
          inverse_class.aliased_associations[foreign_key] = name.to_s
          @owner_class.field(
            foreign_key,
            type: FOREIGN_KEY_FIELD_TYPE,
            identity: true,
            overwrite: true,
            association: self,
            default: nil
          )
        end

        def determine_inverses(other)
          matches = (other || relation_class).relations.values.select do |rel|
            relation_complements.include?(rel.class) &&
              rel.relation_class_name == inverse_class_name
          end
          raise Errors::AmbiguousRelationship.new(relation_class, @owner_class, name, matches) if matches.size > 1

          matches.collect { |m| m.name } unless matches.blank?
        end

        def with_ordering(criteria)
          if order
            criteria.order_by(order)
          else
            criteria
          end
        end

        def query_criteria(id_list)
          crit = relation_class.criteria
          crit = if id_list
                   crit = crit.apply_scope(scope)
                   # A nil in the stored key array would match every document
                   # whose primary key is null or absent, returning documents

View on GitHub (pinned to 0da0e23d71)

When it happens

Trigger: Thrown at lib/mongoid/association/referenced/has_and_belongs_to_many.rb:257 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/1cb5889bc3dfa6f3. Report an issue: GitHub.