Reputation: 2064
I've set up an admin backend in Rails. There are a list of orders. By default when submitted by the end user shows as "processing" on the admin side. If the admin sends out the order he can press the "processing" button and set it to completed.
I'm trying to have a "Delete All Completed Orders" button above the table.
Here is the admin controller:
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
And the index file:
<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't worked with rails in a while
Upvotes: 0
Views: 69
Reputation: 76
You need to create a new controller action in your admin controller like so.
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
Don't forget to add the route to your config/routes.rb
resources :admin do
delete 'destroy_completed_items', on: :collection
end
Then simply call the action from a button/link in your view.
<%= link_to 'Delete All Completed Orders', destroy_completed_items_path, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-danger' %>
Upvotes: 1