You must reload the page to use link_to_add_fields in rails 4

unable to load _contact_fields.html for the first time. I can only work on adding fields when I refresh the page.

application_helper.rb

def link_to_add_fields(name, f, association) new_object = f.object.send(association).klass.new id = new_object.object_id fields = f.fields_for(association, new_object, child_index: id) do |builder| render(association.to_s.singularize + "_fields", f: builder) end link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")}) end 

_form.html.erb

 <%= f.fields_for :contacts do |builder| %> <%= render 'contact_fields', f: builder %> <% end %> <%= link_to_add_fields "Add Fields", f, :contacts %> 

_contact_fields.html.erb

 <fieldset class="field"> <div class="field"> <%= f.label :Contact_Name %><br> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :Contact_Email %><br> <%= f.text_field :email %> </div> <div class="field"> <%= f.label :Contact_Phone %><br> <%= f.text_field :phone_number %> </div> <div class="field"> <%= f.label :Additional_Info %><br> <%= f.text_field :additional_info %> </div> <%= f.hidden_field :id %> <%= f.hidden_field :_destroy %> <%= link_to "Remove Field", "#", class: "remove_fields" %> </fieldset> 

participants.js.coffee

  jQuery -> $('form').on 'click', '.remove_fields', (event) -> $(this).closest('.field').remove() event.preventDefault() $('form').on 'click', '.add_fields', (event) -> time = new Date().getTime() regexp = new RegExp($(this).data('id'), 'g') $(this).before($(this).data('fields').replace(regexp, time)) event.preventDefault() 

contact.rb

 belongs_to :participant,:foreign_key => 'participant_id' 

participant.rb

  has_many :contacts accepts_nested_attributes_for :contacts, allow_destroy: true 

The first time I click the link_to_add_fields # link as shown below http: // localhost: 3000 / participants / new # , if I update the same path after deleting #, I can add the fields.

+5
source share
1 answer

Do you use turboprops? This can happen because Turbolinks loads the page and there is no event for the document to be fired. You want to wait until Turbolinks starts the page: load the event.

To fix this, you can set your javascript to the following:

 $(document).on 'click', 'form .remove_fields', (event) -> event.preventDefault() $(this).closest('.field').remove() $(document).on 'click', 'form .add_fields', (event) -> event.preventDefault() time = new Date().getTime() regexp = new RegExp($(this).data('id'), 'g') $(this).before($(this).data('fields').replace(regexp, time)) 

You do not need jQuery -> with the above code.

+6
source

All Articles