Rails - 复制表单的一部分以提交多个记录

问题描述:

我有许多领域的铁轨形式。 用户希望能够通过单击按钮来复制包含6个字段的表单部分,以便6个字段在页面上出现两次,然后填写字段并提交表单以创建2个新记录。Rails - 复制表单的一部分以提交多个记录

= form_for @item, :html => { :class => "form-horizontal" } do |f| 
    .panel 
     h4 Personal Details 
     .field 
     = f.label :contact_name 
     = f.text_field :contact_name 
     .field 
     = f.label :email_address 
     = f.text_field :email_address 

    .duplicate-section.panel 
     h4 Info 
     .field 
     = f.label :location 
     = f.select :location 
     .field 
     = f.label :time 
     = f.text_field :time 

    = link_to "Add new Info Section", '#' 

的的link_to增加了一个新的.duplicate-section的形式,所以我可以可以在页面上创建额外的字段,但我不知道如何提交表单作为两个单独的记录。

+0

你想创建2个'Item'吗?或只是信息部分(“位置”和“时间”)? – JCorcuera 2014-10-15 18:10:19

+0

2个项目具有相同的名称和电子邮件,但不同的位置和时间 – 2014-10-15 18:15:19

+1

查看您可以在rails中使用的fields_for helper。这与一对多的关系一起工作,可能是你想要的。 – phoet 2014-10-15 19:50:30

要管理这一点,你可以创建封装你型动物记录模式:

运行

rails g model item_wrapper 
bundle exec rake db:migrate 

应用程序/模型/ item_wrapper.rb

class ItemWrapper < ActiveRecord::Base 
    has_many :items 
    accepts_nested_attributes_for :items 
end 

并按照this railscast创建添加和删​​除信息部分按钮。

finnaly你可以通过改变字段的隐藏和填充值为你的项目重复字段自定义JavaScript。

综上所述:

  1. 为您的物品的包装(其中只包含一个id)
  2. 创建的has_many嵌套形式为您的包装形式中的项目(与fields_for)
  3. 创建add_fields,传入三个按钮(CF轨投)
  4. 然后自定义您的JS add_fields,传入三个函数改变的字段复制的内容

干杯

相信这很清楚,我可以根据需求编辑答案,以便更清楚。