Search code examples
ruby-on-railsnested-attributes

Rails, creating associated records along with parent object?


Maybe I don't know how to ask/search for this particular thing, but basically I want to create a few associated models when I create the parent object... say I have the following situation:

I have a Recipe which has_many Ingredient models... is there a way to make them all at once, say 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 like am I totally crazy? There must be some sort of way to do this similarly, without creating the parent model, then all the children... etc, etc.


Solution

  • Quite 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' }
      ]
    })
    

    Note that you need to put "accepts_nested_attributes_for :ingredients" to your Recipe model.