JP Silvashy
JP Silvashy

Reputation: 48555

nested attributes overwrite related model

I have a new action in my controller that I'm passing parameters into so the form for my new object will be filled out with the values from the record the user is duplicating, specifcally this gives the user the opportunity to 'edit' the new content before submitting it.

like this:

def new
  @parent = Recipe.find(params[:parent_id])
  @recipe = Recipe.new(
    :name => @parent.name,
    :description => @parent.description,
    :ingredients => @parent.ingredients,
    :steps => @parent.steps
  )
end

But the problem is that both my ingredients and steps have nested attributes, each with an id of the original. The problem is that because rails is not giving my nested attributes a new id it doesn’t create those records, in fact i think it may try to save over the other ones.

What can I do here? is there a way to pass the @parent.ingredients object to my :ingredients parameter and give it a new id?

Like I know the issue might be the first line in the action

@parent = Recipe.find(params[:parent_id])

Because it's a find it's going to bring the parameters with it, but is there away to find that object, and create new id's for all the objects nested attributes?

Upvotes: 0

Views: 274

Answers (2)

JP Silvashy
JP Silvashy

Reputation: 48555

Wow! my jaw was just on the floor.

@recipe = @parent.dup

Upvotes: 0

bensie
bensie

Reputation: 5403

@recipe = Recipe.new(:name => @parent.name, :description => @parent.description)

@parent.ingredients.each { |i| @recipe.ingredients.build(:name => i.incredient_name, :description => i.ingredient_description) }

Make sense?

Upvotes: 1

Related Questions