我在Rails中设置了管理员后端。有一个订单列表。默认情况下,当最终用户提交时显示为"处理"在管理方面。如果管理员发出订单,他可以按下"处理"按钮并将其设置为已完成。
我试图删除所有已完成的订单"桌子上方的按钮。
这是管理员控制器:
class AdminController < ApplicationController
before_action :authenticate_user!
before_action :ensure_admin_user
def index
@orders = Order.last(5)
@posts = Post.last(5)
@items = Item.last(5)
end
def posts
@posts = Post.all.page(params[:page])
end
def items
end
private
def ensure_admin_user
redirect_to root_path unless current_user.admin?
end
end
索引文件:
<h1>Admin page</h1>
<h3>Orders</h3>
<div class="form-group"><%= link_to 'View all orders', orders_path, class: 'btn btn-default' %><%= link_to 'Delete All Completed Orders', @completed, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-danger' %></div>
<table class="table table-bordered">
<thead>
<tr>
<th>№</th>
<th>Name</th>
<th>Email</th>
<th>Price</th>
<th>Address</th>
<th>Comment</th>
<th>Status</th>
</tr>
</thead>
<% @orders.each do |order| %>
<tr class="order-<%= order.id %><%= ' bg-success' if order.completed %>">
<td><%= link_to order.id, order %></td>
<td><%= order.user.name %></td>
<td><%= order.user.email %></td>
<td><%= order.total_price %></td>
<td><%= truncate(order.address, length: 100, separator: ' ') %></td>
<td><%= truncate(order.comment, length: 100, separator: ' ') %></td>
<% if order.completed %>
<td><%= button_to 'Completed', completed_order_path(order.id), method: :put, remote: true, class: 'btn btn-success' %></td>
<% else %>
<td><%= button_to 'Processing', completed_order_path(order.id), method: :put, remote: true, class: 'btn btn-default' %></td>
<% end %>
</tr>
<% end %>
</table>
Haven一段时间没有使用过rails
答案 0 :(得分:1)
您需要在管理控制器中创建一个新的控制器操作,如此。
class AdminController < ApplicationController
before_action :authenticate_user!
before_action :ensure_admin_user
def index
@orders = Order.last(5)
@posts = Post.last(5)
@items = Item.last(5)
end
....
def destroy_completed_items
Item.destroy_all(completed: true)
redirect_to items_url
end
end
不要忘记将路由添加到config / routes.rb
resources :admin do
delete 'destroy_completed_items', on: :collection
end
然后只需从视图中的按钮/链接调用操作即可。
<%= link_to 'Delete All Completed Orders', destroy_completed_items_path, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-danger' %>