【问题标题】:Seeding with a has_many relationship使用 has_many 关系播种
【发布时间】:2013-11-06 20:50:52
【问题描述】:

我试图在我的数据库中植入与配料有 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)

【问题讨论】:

    标签: ruby-on-rails ruby postgresql ruby-on-rails-4


    【解决方案1】:

    你可以这样做:

    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"})
    

    【讨论】:

      【解决方案2】:

      我不知道如何解决您的问题,但我建议采用这种方法:

      # 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 时,配料也会被保存。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-13
        • 2016-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多