开发者

`accepts_nested_attributes_for` attributes not getting cloned

I want to create a new instance of a model, however I want to bring some parameters from a different record also, essentially duplication most of the parameters into the new instance but leaving some fields blank as well.

Cloning it works (thanks @weppos)

# class RecipesController
def new
  @parent = Recipe.find(params[:parent_id])
  @recipe = @parent.clone
end

And while this does work, it breaks all my nested attributes:

# class Recipe
accepts_nested_attributes_for :ingr开发者_运维知识库edients, :reject_if => lambda { |a| a.values.all?(&:blank?) }, :allow_destroy => true

Like it only saves the new attributes and throws all the old ones away, the ones that should have been duplicated from the other instance.


Use the clone method.

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

If the clone behavior doesn't apply to your need, then you can create a custom method starting from #clone then unsetting all unnecessary properties.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜