【发布时间】:2020-02-11 11:50:51
【问题描述】:
单击模式上的更新后,我正在尝试更新我的列表项。
到目前为止,我所做的是在我的 <tr> 上放置了一个 id 和 contact.id 以供参考,然后在我的 jQuery / Ajax 上使用它。
这是我的_listing.html.erb:
<table class="table" id="contacts">
<% contacts.each do |contact| %>
<%= render partial: 'contacts/contact_item', locals: {contact: contact} %>
<% end %>
</table>
这是我的_contact_item.html.erb:
<tr id="contact_item_<%= contact.id %>">
<td class="middle">
<div class="media">
<div class="media-left">
<%= link_to contact_path(contact), ":data-target" => "#show-contact-modal", ":data-toggle" => "modal", remote: true do %>
<%= image_tag contact.contact_avatar.attached? ? contact.contact_avatar : "100x100.png", class: "media-object img-thumbnail img-rounded mr-3" %>
<% end %>
</div>
<div class="media-body mt-2">
<%= link_to contact_path(contact), ":data-target" => "#show-contact-modal", ":data-toggle" => "modal", remote: true do %>
<h4 class="media-heading"><%= contact.name %></h4>
<% end %>
<address>
<strong><i class="fa fa-map-marker"></i> <%= contact.city %>, <%= contact.state %>, <%= contact.country %>, <%= contact.zip %> </strong><br>
<i class="fa fa-envelope"></i> <%= contact.email %> | <i class="fa fa-mobile"></i> <%= contact.mobile %> | <i class="fa fa-phone"></i> <%= contact.phone %>
</address>
</div>
</div>
</td>
<td class="middle" width="100">
<div class="mt-5">
<%= link_to edit_contact_path(contact), class: "btn btn-outline-secondary btn-circle btn-xs", ":data-target" => "#new-contact-modal", ":data-toggle" => "modal", remote: true do %>
<i class="fa fa-edit"></i>
<% end %>
<div class="btn btn-outline-secondary btn-circle btn-xs delete-contact" data-id="<%= contact.id %>">
<i class="fa fa-times"></i>
</div>
</div>
</td>
</tr>
这是我的update.js.erb:
<% if @success %>
$('#new-contact-modal').modal('hide');
$("tr#contact_item_<%= contact.id %>").html("<%= j render 'contacts/contact_item', contact: @contact %>");
toastr.info('Contact was successfully updated.', 'info')
<% else %>
$(".errors").removeClass('hide');
<% @contact.errors.messages.each do |record| %>
<% key = record.first %>
var html = "<%= j get_error(@contact, key) %>";
$(".error-<%= key.to_s %>").html(html);
<% end %>
$('#save-btn').removeAttr("disabled");
<% end %>
基本上,我试图在更新后关闭模式,但在这种情况下,它根本不会关闭,我需要刷新页面才能看到更新,这不是我想要做的,因为我是使用 ajax 和 jquery 不刷新。
任何人都可以看到我在这里遗漏了什么?
【问题讨论】:
-
它可能比这更复杂......但它应该是
@contact.id这里:$("tr#contact_item_<%= contact.id %>").html("<%= j render 'contacts/contact_item', contact: @contact %>"); -
我认为它与我上面放置的代码相同。不过还是不行。
-
你可能想要渲染部分:
<%= j render partial: 'contacts/contact_item', locals: { contact: @contact } %> -
我尝试添加,它确实关闭了模式,但是它在顶部添加了一个副本以及旧记录。 ` $('#contacts').prepend("");`
标签: javascript jquery ruby-on-rails ajax