JP Silvashy
JP Silvashy

Reputation: 48495

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.

Upvotes: 5

Views: 3951

Answers (2)

Natus Drew
Natus Drew

Reputation: 1896

You also need to add this to your Recipe model

attr_accessible :ingredients_attributes

Upvotes: 1

Heikki
Heikki

Reputation: 15417

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.

Upvotes: 11

Related Questions