Rails by creating related records along with the parent?

Maybe I don’t know how to ask / find this thing, but basically I want to create several related models when I create the parent object ... let's say I have the following situation:

I have Recipe, in which models has_many Ingredient... there is a way to do them all at once, say that this is part of my seed task, for example:

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

Or how am I completely crazy? There must be some way to do it the same way, without creating a parent model, then all the children ... etc. Etc.

+3
source share
2 answers

Very close. See 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: " .

+9

attr_accessible :ingredients_attributes
0

Source: https://habr.com/ru/post/1782885/


All Articles