2009-11-04 119 views
0

我在我的控制器中有一个new动作,我将参数传入,因此我的新对象的表单将填写用户正在复制的记录中的值,具体而言,这会给用户在提交之前有机会“编辑”新内容。嵌套属性覆盖相关模型

这样的:

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

但问题是,无论我ingredientssteps嵌套的属性,每一个与原来的ID。问题是,因为rails没有给我的嵌套属性一个新的ID它不创建这些记录,事实上,我认为它可能会尝试保存在其他的。

我能在这里做什么?有没有办法将@parent.ingredients对象传递给我的:ingredients参数,并给它一个新的ID?

就像我知道的问题可能是在行动的第一线

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

因为它是一个发现它会带给人们的参数,但有没有去发现目标,并创造新的id为所有对象嵌套属性?

回答

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

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

有意义吗?

+0

这是一个有趣的方法,这也是非常棒的逻辑,我可以看到我可以使用它的一些地方。 – 2009-11-04 05:26:30

+0

我75%确定'dup'解决了我的困境,似乎很腥,就像我被欺骗一样。 – 2009-11-04 05:27:10

+0

不客气! – bensie 2009-11-04 16:22:44

0

哇!我的下巴刚刚在地板上。

@recipe = @parent.dup