也许我不知道如何询问/搜索这个特定的东西,但基本上我想在创建父对象时创建一些关联的模型......说我有以下情况:
我有一个 Recipe
其中has_many
Ingredient
模型......有没有办法一次制作它们,比如说这是我的种子任务的一部分,例如:
Recipe.create({
:title => 'apple pie',
:description => 'just apple pie',
:ingredients => {
[0] => {:title => 'apples'},
[1] => {:title => 'sugar'},
[2] => {:title => 'pie crust'}
}
})
或者就像我完全疯了一样?必须有某种类似的方法来执行此操作,而无需创建父模型,然后创建所有子模型……等等。
最佳答案
相当接近。见 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”添加到您的配方模型中。
关于ruby-on-rails - Rails,与父对象一起创建关联记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4568742/