简体   繁体   English

`accepts_nested_attributes_for`属性未克隆

[英]`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 ) 克隆它有效(感谢@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 :ingredients, :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. 使用clone方法。

@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. 如果克隆行为不适用于您的需要,则可以从#clone开始创建自定义方法,然后#clone所有不必要的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM