开发者

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 param开发者_StackOverflow社区eter 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?


@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?


Wow! my jaw was just on the floor.

@recipe = @parent.dup
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜