Rails,与父对象一起创建关联记录?

时间:2010-12-31 07:21:21

标签: ruby-on-rails nested-attributes

也许我不知道如何询问/搜索这个特定的东西,但基本上我想在创建父对象时创建一些相关的模型...说我有以下情况:

我有Recipehas_many Ingredient个模型......有没有办法让它们一次完成,比如说这是我种子任务的一部分,例如:

Recipe.create({
  :title => 'apple pie',
  :description => 'just apple pie',
  :ingredients => {
    [0] => {:title => 'apples'},
    [1] => {:title => 'sugar'},
    [2] => {:title => 'pie crust'}
  }
})

或者就像我完全疯了一样?必须有某种方式来做同样的事情,不创建父模型,然后所有的孩子......等等。

2 个答案:

答案 0 :(得分:10)

非常接近。见http://apidock.com/rails/v3.0.0/ActiveRecord/NestedAttributes/ClassMethods

Recipe.create({
  :title => 'apple pie',
  :description => 'just apple pie',
  :ingredients_attributes => [
    { :title => 'apples' },
    { :title => 'sugar' },
    { :title => 'pie crust' }
  ]
})

请注意,您需要将“accepts_nested_attributes_for:ingredients”添加到您的食谱模型中。

答案 1 :(得分:0)

您还需要将其添加到您的食谱模型

attr_accessible :ingredients_attributes
相关问题