unable to load _contact_fields.html for the first time . i can work on adding fields only 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
For the first time when i click on link_to_add_fields # is passed as shown below http://localhost:3000/participants/new# if i refresh the same path after removing the # the i am able to add fields .
Are you using turbolinks? This could be happening because Turbolinks is loading the page, and there isn't a document ready event being fired. You want to wait until Turbolinks fires the page:load event.
To fix this, you can adjust 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 the jQuery -> with the above code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With