nested_form 在错误消息后显示额外字段

nested_form shows extra fields after error messages

我正在使用 simple_nested_form_for 构建带有嵌套字段的表单。字段是动态添加的

呈现错误的表单时(通过 create)嵌套字段出错。

相同的嵌套字段多次显示,并且 name 元素中的索引值错误。

例如嵌套字段中的FormBuilder index最初是一个随机数,例如1454793731550。重新渲染后,它们只是变成正常增量 0-n.

为什么 FormBuilder index 最初是随机数?

有什么建议吗?

  def new
    @transaction = current_company.transactions.build
    @transaction.subtransactions.build
  end

  def create
    @transaction = current_company.transactions.new(transaction_params)

    if @transaction.save
      redirect_to dashboard_url
    else
      @transaction.subtransactions.build
       render :action => 'new'
    end

index是嵌套字段的child_index。这只是 Rails 单独识别 HTML 表单元素的各种字段名称的一种方式:

<%= f.fields_for :association do |a| %>
  <%= a.text_field :x %> #-> "child_index" id will either be sequential (0,1,2)
<% end %>

child_index无所谓。只要它是唯一的,就应该按如下方式传递给控制器​​:

params: {
  association_attributes: {
    0: { x: "y", z: "0" },
    1: { ... }
  }
}

一个经常使用的技巧是将 child_index 设置为 Time.now.to_i,这允许您添加超出范围的新字段:

<%= f.fields_for :association, child_index: Time.now.to_i do |a| %>

关于您的 new 操作,可能的问题是您的 subtransactions 对象每次都在构建(无论实例是否填充了以前的数据)。

我们以前遇到过这个问题,我相信我们有条件地解决了它:

def new
  @transaction = current_company.transactions.build
  @transaction.subtransactions.build unless @transaction.errors.any?

这应该在整个提交过程中保持对象的完整性。 IE 如果发生错误,我相信 Rails 将关联对象存储在内存中(就像它对父对象所做的那样)。