Ruby on Rails中NoMethodError求助:路由控制器配置正确仍报错
解决Rails渲染JSON时出现的NoMethodError(undefined method `type')
已配置正确的路由和控制器动作,但调用/restaurants接口时触发NoMethodError,提示undefined method 'type' for #<Restaurant:0x00007fb711a07628>,以下是相关代码与错误信息:
相关代码
路由配置
get "/restaurants", to: "restaurants#index"
控制器动作
def index resto = Restaurant.all render json: resto, status: :ok end
错误信息
浏览器端错误
NoMethodError in RestaurantsController#index undefined method `type' for #<Restaurant:0x00007fb711a07628> Extracted source (around line #4): def index resto=Restaurant.all ( render json: resto,status: :ok) # this is the line throwing error end end
控制台错误日志
Use Ctrl-C to stop Started GET "/restaurants" for ::1 at 2022-08-16 22:26:25 +0530 (0.7ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC Processing by RestaurantsController#index as HTML Restaurant Load (1.2ms) SELECT "restaurants".* FROM "restaurants" ↳ app/controllers/restaurants_controller.rb:4:in `index' [active_model_serializers] Rendered ActiveModel::Serializer::CollectionSerializer with ActiveModelSerializers::Adapter::Attributes (12.1ms) Completed 500 Internal Server Error in 38ms (ActiveRecord: 7.5ms | Allocations: 17269)
问题原因与解决方法
从控制台日志能看到,错误由active_model_serializers(AMS)触发。AMS在序列化模型时,默认逻辑可能误判需要type字段(比如单表继承场景),或者缺少对应模型的序列化器导致异常。
方法一:创建Restaurant序列化器
终端执行生成命令:
rails generate serializer Restaurant
打开生成的app/serializers/restaurant_serializer.rb,指定需要返回的字段:
class RestaurantSerializer < ActiveModel::Serializer attributes :id, :name, :address # 替换为你的模型实际字段 end
方法二:使用Rails原生JSON渲染
修改控制器动作,绕过AMS直接用原生方法指定返回字段:
def index resto = Restaurant.all render json: resto.as_json(only: [:id, :name, :address]), status: :ok end
方法三:检查单表继承配置
如果项目未使用单表继承,确认Restaurant模型没有继承自需要type字段的父类,或者数据库表中是否存在多余的type字段,若有且不需要则移除该字段。
内容的提问来源于stack exchange,提问作者user19539895
相关产品推荐
相关产品推荐

