5

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

我有一个Recipe哪些has_many Ingredient模型......有没有办法一次制作它们,比如说这是我的种子任务的一部分,例如:

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

或者就像我完全疯了?必须有某种类似的方法来执行此操作,而不创建父模型,然后创建所有子模型……等等。

4

2 回答 2

11

相当接近。请参阅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”放入您的配方模型。

于 2010-12-31T07:30:21.777 回答
1

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

attr_accessible :ingredients_attributes
于 2014-02-09T19:40:33.843 回答