Ajax создает дубликаты форм до перезагрузки страницы - PullRequest
0 голосов
/ 24 июня 2018

В нижней части страницы индекса появляется простая форма, использующая Ajax для отправки формы и перезагрузки списка индексов. По какой-то причине при отмене формы или переходе между страницами сайта и повторном открытии формы создаются дубликаты. Я думаю, что форма дублируется каждый раз, когда вы переходите на новую страницу сайта, так как отмена просто перенаправляет обратно на страницу индекса снова. У меня также есть такая же настройка формы AJAX на другой странице, которая имеет такую ​​же проблему.

Это происходит в приложении Rails 4 с использованием Foundation

index.html.erb:

<p id="notice"><%= notice %></p>

<h1>Listing Scope Times</h1>

<table>
  <thead>
    <tr>
      <th>Job</th>
      <th>Scope</th>
      <th>Week</th>
      <th>Hours</th>
      <th>Completion Rate</th>
      <th colspan="1"></th>
    </tr>
  </thead>

  <%= render "scope_times/times_list.html.erb" %>
</table>

<br>

<%= link_to(new_scope_time_path, id: 'new_scope_time_link', class: 'button tiny radius', remote: true) do %>
  Add New Scope Time Now
<% end %>

<br>

_new_scope_time_form.html.erb:

<%= simple_form_for @scope_time, html: { :class => 'form-horizontal' }, remote: true do |f| %>
    <%= f.input :completion_rate, label: "% Completed", input_html: { :class => "avg"} %>
    <%= f.input :hours, label: "Hours", input_html: { :class => "avg"} %>
    <%= f.input :week, as: :date, label: "Week", input_html: { :class => "avg"} %>
    <%= f.association :scope, collection: Scope.all,:label_method => lambda { |scope| "#{scope.job.name} | #{scope.description}" }, label: "Scope", input_html: { :class => "avg"} %>
    <p>&nbsp</p>
    <div class="form_actions">
        <%= f.submit nil, class: 'button tiny radius' %>
        <%= link_to 'Cancel', scope_times_path, class: 'button tiny radius alert' %>
    </div>
<% end %>

new.js.erb:

$('#new_scope_time_link').hide().after('<%= j render("new_scope_time_form") %>');

create.js.erb:

$('#new_scope_time').remove();
$('#new_scope_time_link').show();
$('#times_list').replaceWith('<%= j render("scope_times/times_list") %>');

Обновление страницы устраняет проблему, даже если переход по ссылке на ту же страницу не будет. Есть идеи, почему это происходит?

1 Ответ

0 голосов
/ 24 июня 2018

Имеется в виду несколько вещей: -

1) -> Рекомендуется использовать локальные переменные с частичным, а также частичным именем, не должно содержать .html.erb, пока вы определяете render partila: ''

при условии, что @scopes содержит списки областей действия и определено в действии index, оно должно быть

<%= render "scope_times/times_list", scopes: @scopes %>

2) -> создать частичное для _add_new_scope_link.html.erb

  <%= link_to(new_scope_time_path, id: 'new_scope_time_link', class: 'button tiny radius', remote: true) do %>
  Add New Scope Time Now
  <% end %>

Index.html.erb

<p id="notice"><%= notice %></p>

<h1>Listing Scope Times</h1>

<table>
  <thead>
    <tr>
      <th>Job</th>
      <th>Scope</th>
      <th>Week</th>
      <th>Hours</th>
      <th>Completion Rate</th>
      <th colspan="1"></th>
    </tr>
  </thead>
  <tbody id="scope_times_lists">
    <%= render "scope_times/times_list.html.erb" %>
  </tbody>
</table>

<br>
<div id="add_new_scope_link">
  <%= render 'add_new_scope_link'%>
</div>

<br>

new.js.erb

#replace form and remove link
$('#new_scope_time_link').html(<%= j render 'new_scope_time_form' %>);

create.js.erb:

$('#new_scope_time').remove(); #remove form
$('#scope_times_lists').html("<%= j render 'scope_times/times_list', scopes: @scopes %>"); #refresh scopes lists including new created list
$('#add_new_scope_link').html("<%= j render 'add_new_scope_link'%>"); #add link again to create new form 
...