nested_form:所有添加的字段具有相同的名称

时间:2013-11-04 03:12:19

标签: ruby-on-rails simple-form nested-forms activemodel nested-form-for

我有一个复杂的形式,我使用ActiveModel对象来验证一些通用字段:

  class FormReportPivot
   include ActiveModel::Validations
   include ActiveModel::Conversion
   extend ActiveModel::Naming

   attr_accessor :name, :pages, :columns, :rows, :table, 
   :pages_aggregation, :columns_aggregation, :rows_aggregation, :table_aggregation

   def initialize(attributes = {})
    attributes.each do |name, value|
      public_send("#{name}=", value)
    end
   end

   def persisted?
    false
   end

  end

我有这个字段的nested_form:

 = f.simple_fields_for :pivots do |pivots_builder|
  = render :partial => 'pivot_fields', :locals => { :pivots_builder => pivots_builder }
  = f.link_to_add "Add pivot", :pivots, model_object: FormReportPivot.new, class: "btn blue"

部分:

  = pivots_builder.input :name, input_html: {:class => "m-wrap"}, 
    placeholder: t('.name')
  = pivots_builder.input :columns, collection: @form_report.columns_collection, :include_blank => false, input_html: {:class => "m-wrap chosen", multiple: true}
  = pivots_builder.input :rows, collection: @form_report.columns_collection, :include_blank => false, input_html: {:class => "m-wrap chosen", multiple: true}
  = pivots_builder.input :table, collection: @form_report.columns_collection, :include_blank => false, input_html: {:class => "m-wrap chosen", multiple: true}
  = pivots_builder.input :table_aggregation, collection: FormReport::AGGREGATING_FUNCTIONS, :include_blank => false, input_html: {:class => "m-wrap chosen"}

但是当我点击“添加支点”时,我会获得具有相同ID并且没有时间戳的相同字段:

 <input class="string optional m-wrap m-wrap" 
 id="form_report_pivots_attributes_name" 
 name="form_report[pivots_attributes][name]" placeholder="" title="">

1 个答案:

答案 0 :(得分:1)

只包括fields_for:fields_for:pivots中的new_pivots 和嵌套表单用正确的时间戳替换new_pivots:

形式:

  = f.simple_fields_for :pivots do |pivots_builder|
    = render :partial => 'pivot_fields', :locals => { :f => pivots_builder }
  = f.link_to_add "Add pivot", :pivots, model_object: FormReportPivot.new, class: "btn blue"

部分:

  .well
    = f.simple_fields_for :new_pivots do |pf|
      = pf.input :name, input_html: {:class => "m-wrap"}, 
        placeholder: t('.name')
      = pf.input :columns, collection: @form_report.columns_collection, :include_blank => false, input_html: {:class => "m-wrap chosen", multiple: true}
      = pf.input :rows, collection: @form_report.columns_collection, :include_blank => false, input_html: {:class => "m-wrap chosen", multiple: true}
      = pf.input :table, collection: @form_report.columns_collection, :include_blank => false, input_html: {:class => "m-wrap chosen", multiple: true}
      = pf.input :table_aggregation, collection: FormReport::AGGREGATING_FUNCTIONS, :include_blank => false, input_html: {:class => "m-wrap chosen"}