mongodb/mongoid · error · ArgumentError
Cannot build belongs_to association from array
Error message
Cannot build belongs_to association from array
What it means
Error "Cannot build belongs_to association from array" thrown in mongodb/mongoid.
Source
Thrown at lib/mongoid/association/referenced/belongs_to/buildable.rb:31
# relation.build(meta, attrs)
#
# @param [ Object ] base The base object.
# @param [ Object ] object The object to use to build the association.
# @param [ String ] type The type of the association.
# @param [ nil ] selected_fields Must be nil.
#
# @return [ Document ] A single document.
def build(_base, object, type = nil, selected_fields = nil)
return object unless query?(object)
# Handle array from $lookup aggregation (returns array even for belongs_to)
if object.is_a?(Array)
first = object.first
case first
when nil, Mongoid::Document then return first
when Hash then return Factory.execute_from_db(klass, first, nil, selected_fields,
execute_callbacks: false)
else raise ArgumentError, 'Cannot build belongs_to association from array'
end
end
# Handle single hash from $lookup with $unwind
if object.is_a?(Hash)
return Factory.execute_from_db(klass, object, nil, selected_fields, execute_callbacks: false)
end
execute_query(object, type)
end
private
def execute_query(object, type)
query_criteria(object, type).take
end
def query_criteria(object, type)View on GitHub (pinned to 0da0e23d71)
When it happens
Trigger: Thrown at lib/mongoid/association/referenced/belongs_to/buildable.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/c652a4006b7d04a0.
Report an issue: GitHub.