Ruby on Rails中Recipes接口GET请求TypeError报错求助
问题分析与解决方案
问题定位
报错TypeError: nil is not a symbol nor a string出现在RecipesController#index,但Users接口正常,结合代码来看,核心原因是**try是Ruby的内置方法名**,将其作为Recipe模型的属性名会和ActiveModel::Serializer的序列化逻辑冲突,导致序列化过程中出现类型错误。
解决步骤
1. 验证问题
临时修改RecipeSerializer,注释掉:try属性:
class RecipeSerializer < ActiveModel::Serializer attributes :id, :title, :image, :link, :cuisine, :ingredients, :date, :favorite, :made # 注释掉 :try end
重启服务器后测试Recipes接口,如果请求恢复正常,即可确认是:try字段的问题。
2. 修改数据库字段名
生成迁移文件重命名冲突字段:
rails generate migration RenameTryToWantToTryInRecipes
编辑生成的迁移文件(路径:db/migrate/[timestamp]_rename_try_to_want_to_try_in_recipes.rb):
class RenameTryToWantToTryInRecipes < ActiveRecord::Migration[7.0] def change rename_column :recipes, :try, :want_to_try end end
执行迁移:
rails db:migrate
3. 更新序列化器
将RecipeSerializer中的:try替换为新字段名(比如:want_to_try):
class RecipeSerializer < ActiveModel::Serializer attributes :id, :title, :image, :link, :cuisine, :ingredients, :date, :favorite, :want_to_try, :made end
4. 测试接口
重启Rails服务器,再次发起Recipes接口的GET请求,应该能正常返回JSON数据。
补充说明
避免使用Ruby/Rails的关键字或内置方法名作为模型属性名,比如try、class、method等,这类命名会引发隐性的冲突问题。
内容的提问来源于stack exchange,提问作者melissaloveshotdogs
相关产品推荐
相关产品推荐

