Rails执行db:seed报错:模型关联配置存在未知:through键错误
错误排查及修复方案
直接报错原因
Rails的belongs_to关联不支持:through参数,你在Dish模型第4行写的belongs_to :user, through: :cuisine属于非法语法,这就是报错直接提示Unknown key: :through的根源。
第二个隐含关联错误
User模型中has_many :dishes, through: :cuisine的through参数值需要和前面定义的关联名对应,你前面写的是has_many :cuisines,所以这里要改成复数through: :cuisines,否则后续调用user.dishes时会触发关联找不到的错误。
修正后的模型代码
User 模型
class User < ApplicationRecord has_secure_password has_many :cuisines has_many :dishes, through: :cuisines # 修正为复数cuisines has_many :comments end
Dish 模型
class Dish < ApplicationRecord belongs_to :cuisine has_many :comments # 替换错误的belongs_to写法,如果需要通过菜系关联获取用户,用has_one has_one :user, through: :cuisine # 也可以用委托写法更简洁:delegate :user, to: :cuisine end
Cuisine、Comment模型代码无需改动。
Seed文件优化建议
你现有seed里硬编码了user_id:1、cuisine_id:1,后续如果数据顺序变化容易报错,可修改为动态关联创建:
adi = User.create(name: "Adi", username: "adi3", password: "password") # 通过用户关联创建菜系,自动填充user_id italian = adi.cuisines.create(country: "Italy", picture: "https://www.delonghi.com/Global/recipes/multifry/pizza_fresca.jpg") # 通过菜系关联创建菜品,自动填充cuisine_id pizza = italian.dishes.create(name: "Pizza", picture: "https://d1uz88p17r663j.cloudfront.net/original/4274048cd5f17c49dfee280f77a3739d_Cheese-Pizza_HB-2.jpg", ingredients: "flour, water, yeast, oil, salt, cheese, olives", directions: "mix everything together and add toppings", cook_time: "30 min", yield: "1 big pizza") adi_pasta = adi.dishes.create(name: "Pomodoro Pasta", picture: "https://lh3.googleusercontent.com/_mkIjqOA29bzih8kz98RjBqf6KbLaan2ReyAzM2-Vj7SPDWGF24vPLz3zdTiwRdHaDdn6ed5kHdUUWkyoOQ83ZE=s640-c-rw-v1-e365", ingredients: "olive oil, garlic, basil, tomato, pasta", directions: "mix everything, cook pasta and top it up", cook_time: "20 min", yield: "4 portions", cuisine: italian) # 通过用户关联创建评论,自动填充user_id、dish_id adi.comments.create(content: "Great easy tomato pasta", dish: adi_pasta)
内容的提问来源于stack exchange,提问作者DevA
相关产品推荐
相关产品推荐

