需要重新加载页面才能在rails 4中使用link_to_add_fields

时间:2015-06-25 10:41:14

标签: ruby-on-rails ruby

无法首次加载_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#如果我在删除#后刷新相同的路径,我可以添加字段。

1 个答案:

答案 0 :(得分:6)

你在使用turbolinks吗?这可能会发生,因为Turbolinks正在加载页面,并且没有文档就绪事件被触发。你想等到Turbolinks触发页面:加载事件。

要解决此问题,您可以将javascript调整为以下内容:

$(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))

你不需要jQuery - &gt;使用上面的代码。