我遇到了一个Rails AJAX应用程序的问题让我感到困惑,尽管看起来非常简单!我在一个简单的销售点应用程序中处理class Order
。正在进行请求,因为订单将在页面刷新时删除(但我没有刷新@orders
),因为我认为我在destroy.js.erb
中指定。
<div id="orders">
<%= render 'orders/index' %>
</div>
<%= link_to 'New Order', new_order_path, remote: true %>
<div id="order-form" style="display:none;"></div>
<% if @orders.any? %>
<% @orders.each do |order| %>
<%= link_to "Show #{order.id}", order_path(order), class: "something" %>
<%= link_to "Delete #{order.id}", order_path(order), method: :delete, class: "something" %>
<%= link_to "Delete order with ajax", order_path(order), remote: true, method: :delete %>
<% end %>
<% else %>
<p>No orders yet</p>
<% end %>
//When deleting order on order index - render orders again.
$('#orders').html("<%= j (render 'orders/index') %>");
orders_controller.rb
class OrdersController < ApplicationController
respond_to :html, :js
def index
@orders = Order.paginate(page: params[:page])
if params[:search]
@orders = Order.search(params[:search]).order("created_at DESC")
else
@orders = Order.all.order('created_at DESC')
end
end
def destroy
@order = Order.find(params[:id])
if @order.destroy
flash[:notices] = ["Order was successfully deleted"]
redirect_to orders_path
else
flash[:notices] = ["Order could not be deleted"]
render order_path(@order)
end
end
我怀疑问题出在我的orders_controller
破坏或索引操作中,但我对在Rails中使用AJAX的一些方法有点不清楚。
答案 0 :(得分:1)
可能是因为在您销毁之后,您将重定向到索引路径
答案 1 :(得分:1)
我没有刷新
@orders
您的JS
可能无法解雇,您需要following:
def destroy
@order = Order.find params[:id]
respond_to do |format|
if @order.destroy
format.js
format.html { redirect_to orders_path, notice: "Order was successfully deleted" }
else
format.js
format.html { render order_path(@order), notice: "Order could not be deleted" }
end
end
end
这将触发app/views/orders/destroy.js.erb
,这在您的OP中似乎没问题。
答案 2 :(得分:1)
尝试将销毁操作更新为
@order = Order.find(params[:id])
@order.destroy
@orders=Order.all
删除所有重定向 会工作的。