搭建带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
相关产品推荐
相关产品推荐

