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

JP *_*shy 4 ruby-on-rails nested-attributes

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

我有Recipe哪些has_many Ingredient车型?有没有一种方法,使他们一次全部,说这是我的例子种子任务的一部分:

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

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

Hei*_*kki 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' }
  ]
})
Run Code Online (Sandbox Code Playgroud)

请注意,您需要将"accepts_nested_attributes_for:ingredients"放入Recipe模型中.