Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 687
JP Silvashy Avatar asked Dec 31 '10 07:12

JP Silvashy


2 Answers

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.

like image 152
Heikki Avatar answered Nov 16 '22 17:11

Heikki


You also need to add this to your Recipe model

attr_accessible :ingredients_attributes
like image 23
Natus Drew Avatar answered Nov 16 '22 16:11

Natus Drew