ruby-on-rails – 以has_many关系播种
发布时间:2020-12-17 01:47:37 所属栏目:百科 来源:网络整理
导读:我试图使用与成分具有has_many关系的食谱来种植我的数据库.成分表有4行.但是我的代码却遇到了错误.这是我的代码.我对rails很新,但还没找到解决方案.我正在使用Rails 4和Postgres. 错误 rake aborted!Ingredient(#xxxxxxx) expected,got Hash(#xxxxxxx)Tasks:
我试图使用与成分具有has_many关系的食谱来种植我的数据库.成分表有4行.但是我的代码却遇到了错误.这是我的代码.我对rails很新,但还没找到解决方案.我正在使用Rails 4和Postgres.
错误 rake aborted! Ingredient(#xxxxxxx) expected,got Hash(#xxxxxxx) Tasks: TOP => db:seed (See full trace by running task with --trace) 食谱 class Recipe < ActiveRecord::Base attr_accessible :title,:descrition,:image has_many :ingredients accepts_nested_attributes_for :ingredients end 成分 class Ingredient < ActiveRecord::Base attr_accessible :measure,:modifier,:item,:note belongs_to :recipe end Seed.rb(这里的例子有2种成分,每种成分的每一行都有含量) Recipe.create( [{ title: "Recipe title here",description: "This is the description",image: "theimage.jpg",ingredients_attributes: [{measure: "1cup",modifier: "canned",item: "Mushrooms",note: "drained"},{measure: "1lb",modifier: "sliced",item: "Bacon",note: "previously cooked"},] }],without_protection: true) 解决方法
你可以这样做:
recipe = Recipe.create({ title: "Recipe title here",image: "theimage.jpg"}) recipe.ingredients.create(measure: "1cup",note: "drained") recipe.ingredients.create(measure: "1lb",note: "previously cooked"}) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |