4

我试图用与配料有 has_many 关系的食谱播种我的数据库。成分表有 4 行。但是,我的代码一直遇到错误。这是我的代码。我对 Rails 还很陌生,但还没有找到解决方案。我正在使用带有 Postgres 的 Rails 4。

错误

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)
4

2 回答 2

13

你可以这样做:

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"})
于 2013-11-06T21:03:52.210 回答
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 时,配料也会被保存。

于 2013-11-06T21:02:32.750 回答