第一次无法加载_contact_fields.html。只有在刷新页面后,我才能添加字段。
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
第一次点击link_to_add_fields时,#作为参数传递,如下所示: http://localhost:3000/participants/new# 如果我在去掉#后刷新相同的路径,那么我就可以添加字段。