You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

搭建带Blueprint Serializer的Rails API连MongoDB时请求报错,如何解决?

问题解决:Rails API返回JSON时出现NoMethodError

核心原因

错误提示undefined method '_id' for #<Mongoid::Criteria>,是因为Movie.all返回的是Mongoid::Criteria对象(延迟查询的集合代理),而非实际的Movie实例数组。Blueprinter尝试直接对这个代理对象调用_id方法,自然会报错。

修复步骤

1. 执行查询并转换为实例数组

修改控制器代码,将Movie.all转为数组,确保Blueprinter能遍历实际的Movie实例:

module Api
    module V1
        class MoviesController < ApplicationController
            def index
                movies = Movie.all.to_a # 转为数组,触发查询

                render json: MovieBlueprint.render_as_hash(movies)
            end
        end
    end
end

2. 修正字段不一致问题

你的MovieBlueprint里声明了:genre字段,但Movie模型中并没有定义这个字段。需要二选一:

  • 要么在模型中添加genre字段:
    class Movie
      include Mongoid::Document
      
      field :title, type: String
      field :description, type: String
      field :director, type: String
      field :genre, type: String # 添加此字段
    end
    
  • 要么从Blueprint中移除:genre字段:
    class MovieBlueprint < Blueprinter::Base
        identifier(:_id)
      
        fields(
          :title,
          :description,
          :director
          # 去掉:genre
        )
    end
    

3. 验证路由与请求

你的路由配置是正确的,请求GET http://localhost:3000/api/v1/movies.json可以正常匹配到api/v1/movies#index。修复后重新启动服务器,再次发起请求即可获取所有电影的JSON数据。

内容的提问来源于stack exchange,提问作者kellen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:21:52