I have one complicated form where i use ActiveModel object for validating some generic fields:

  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

I have nested_form for this fields:

 = 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"

Partial:

  = 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"}

But when i'm clicking "Add pivot" i get same fields with same name with same id and without timestamp:

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

解决方案

Just included fields_for :new_pivots in fields_for :pivots and Nested Form replace new_pivots with right timestamp:

Form:

  = 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"

Partial:

  .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"}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top