我尝试使用与成分具有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
成分</ P>
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)
答案 0 :(得分:12)
你可以这样做:
recipe = Recipe.create({
title: "Recipe title here",
description: "This is the description",
image: "theimage.jpg"})
recipe.ingredients.create(measure: "1cup", modifier: "canned", item: "Mushrooms", note: "drained")
recipe.ingredients.create(measure: "1lb", modifier: "sliced", item: "Bacon", note: "previously cooked"})
答案 1 :(得分:0)
我不知道如何修复你的解决方案,但我建议采用这种方法:
# initialize new recipe
recipe = Recipe.new(title: "", description: "", image: "")
# build ingredients
recipe.ingredients.build(measure: "", modifier: "", item: "", note: "")
recipe.ingredients.build(measure: "", modifier: "", item: "", note: "")
recipe.save
当您在食谱上运行.save时,成分也会被保存。