Jquery Rails通过AJAX删除模型对象
我正在尝试使用Ajax远程销毁一个对象。这就是我所做的: 这是ProductsController中的销毁操作Jquery Rails通过AJAX删除模型对象,jquery,ruby-on-rails,ajax,button,destroy,Jquery,Ruby On Rails,Ajax,Button,Destroy,我正在尝试使用Ajax远程销毁一个对象。这就是我所做的: 这是ProductsController中的销毁操作 def destroy @product = Product.find(params[:id]) @product.destroy respond_to do |format| format.html {redirect_to products_path, success: 'Product destroyed successfully'}
def destroy
@product = Product.find(params[:id])
@product.destroy
respond_to do |format|
format.html {redirect_to products_path, success: 'Product destroyed successfully'}
format.js {}
end
end
这是destroy.js.erb内部产品视图
$(this).closest('tr').remove()
与按钮的交互位于具有以下模板的页面中:
索引模板:
<table class="table table-hover products">
<thead>
<tr>
<th>Product</th>
<th>Stock</th>
<th>Cost</th>
<th>Price</th>
<th>Sell</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<%= render @products %>
</tbody>
</table>
<br/>
<br/>
产品
股票
成本
价格
卖
删除
这是我们的产品模板
<tr>
<td>
<%= link_to product.title, edit_product_path(product) %>
</td>
<td>
<%= product.stock %>
</td>
<td>
<%= product.cost %>
</td>
<td>
<%= product.price %>
</td>
<td>
<%= button_to 'Sell Product', new_product_sale_path(product), method: :get, class: 'btn btn-secondary' %>
</td>
<td>
<%= button_to "Delete Product", product_path(product), remote: true,
method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-secondary" %>
</td>
</tr>
销毁工作正常,但html不会相应更新。我错过了什么?谢谢
delete.js.erb中的这个
没有意义。您必须以某种方式唯一地标记每一行,例如通过id
您的_产品模板将如下所示:
<tr id="row_<%= product_id %>">
<td>
<%= link_to product.title, edit_product_path(product) %>
</td>
<td>
<%= product.stock %>
</td>
<td>
<%= product.cost %>
</td>
<td>
<%= product.price %>
</td>
<td>
<%= button_to 'Sell Product', new_product_sale_path(product), method: :get, class: 'btn btn-secondary' %>
</td>
<td>
<%= button_to "Delete Product", product_path(product), remote: true,
method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-secondary" %>
</td>
</tr>
你的destroy.js.erb应该是
$("#row_<%= @product.id %>").remove();
$(“#行”).remove();
我希望您能理解这一点。使用DOMid来定位要删除的元素是一种很好的做法。例如:
和在destroy.js.erb$('#').remove()实际上,这是对象的引用,因此它在destroy.js.erb中不可用。
您可以为产品部分中的每个tr提供唯一的id
例如: