Rails - duplicating part of a form to submit multiple posts

I have a rails shape with many fields. The user wants to be able to duplicate a section of a form containing 6 fields by clicking a button so that 6 fields appear twice on the page, then fill in the fields and submit the form, creating two new records.

= 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 adds a new form .duplicate-section

to the form, so I can create additional fields on the page, but I don't know how to submit the form as two separate records.

+3


source to share


1 answer


To manage this, you can create a model that encapsulates your differents entries:

run

rails g model item_wrapper
bundle exec rake db:migrate

      

app / models / item_wrapper.rb

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

      

And follow this railscast to create add and remove information buttons.



finnaly you can customize javascript generated by changing fields to hidden and fill values ​​for your duplicate fields.

Summarizing:

  • create a wrapper for your elements (which only contains an id)
  • create a nested has_many form for your elements inside your wrapper form (with for_fields)
  • create add_fields button (cf rails cast)
  • then set up js add_fields function to change duplicate content fields

Greetings

Considering that this is clear enough, I can edit the answer to be clearer on demand.

0


source







All Articles