{"record":{"id":"c652a4006b7d04a0","repo":"mongodb/mongoid","slug":"cannot-build-belongs-to-association-from-array","errorCode":null,"errorMessage":"Cannot build belongs_to association from array","messagePattern":"Cannot build belongs_to association from array","errorType":"exception","errorClass":"ArgumentError","httpStatus":null,"severity":"error","filePath":"lib/mongoid/association/referenced/belongs_to/buildable.rb","lineNumber":31,"sourceCode":"          #   relation.build(meta, attrs)\n          #\n          # @param [ Object ] base The base object.\n          # @param [ Object ] object The object to use to build the association.\n          # @param [ String ] type The type of the association.\n          # @param [ nil ] selected_fields Must be nil.\n          #\n          # @return [ Document ] A single document.\n          def build(_base, object, type = nil, selected_fields = nil)\n            return object unless query?(object)\n\n            # Handle array from $lookup aggregation (returns array even for belongs_to)\n            if object.is_a?(Array)\n              first = object.first\n              case first\n              when nil, Mongoid::Document then return first\n              when Hash then return Factory.execute_from_db(klass, first, nil, selected_fields,\n                                                            execute_callbacks: false)\n              else raise ArgumentError, 'Cannot build belongs_to association from array'\n              end\n            end\n\n            # Handle single hash from $lookup with $unwind\n            if object.is_a?(Hash)\n              return Factory.execute_from_db(klass, object, nil, selected_fields, execute_callbacks: false)\n            end\n\n            execute_query(object, type)\n          end\n\n          private\n\n          def execute_query(object, type)\n            query_criteria(object, type).take\n          end\n\n          def query_criteria(object, type)","sourceCodeStart":13,"sourceCodeEnd":49,"githubUrl":"https://github.com/mongodb/mongoid/blob/0da0e23d71adfbad31128c18e5e2c8c301c6f7c4/lib/mongoid/association/referenced/belongs_to/buildable.rb#L13-L49","documentation":"Error \"Cannot build belongs_to association from array\" thrown in mongodb/mongoid.","triggerScenarios":"Thrown at lib/mongoid/association/referenced/belongs_to/buildable.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"}