我按照状态对订单列表进行排序。现在在我看来,我有按钮按每个类别进行过滤,但我想实现一个下拉菜单。如果有人有任何建议,我想清理我对它们的排序方式。
admin_controller
def dashboard
@user = current_user
@all_orders = Order.all
if params[:status]
if params[:status] == "ordered"
@orders = Order.find_status("ordered")
elsif params[:status] == "paid"
@orders = Order.find_status("paid")
elsif params[:status] == "completed"
@orders = Order.find_status("completed")
elsif params[:status] == "cancelled"
@orders = Order.find_status("cancelled")
end
else
@orders = Order.all
end
end
仪表板上的视图。现在它的按钮,我们想要一个下降的菜单。
<h3>All Orders</h3>
<%= button_to "Ordered", admin_dashboard_path, method: :get, params:
{status: "ordered"}, class: "btn btn-small"%>
<%= button_to "Paid", admin_dashboard_path, method: :get, params:
{status: "paid"}, class: "btn btn-small"%>
<%= button_to "Completed", admin_dashboard_path, method: :get, params:
{status: "completed"}, class: "btn btn-small"%>
<%= button_to "Cancelled", admin_dashboard_path, method: :get, params:
{status: "cancelled"}, class: "btn btn-small"%>
答案 0 :(得分:0)
对于选择框,您可以执行以下操作。创建一个表单,但使用get方法而不是post,所以它只是在路径中添加一个查询字符串。我在这里包括bootstrap类只是为了展示如何添加类。
[x for x in s.split() if x.startswith('x') and x.endswith('z')]
对于控制器,您无需将其嵌套在if params [:status]块中,因为在您的示例中,这似乎是多余的。您也可以使用case语句而不是一堆if语句,但对于4而言,这并不是什么大问题。我不知道find_status是你创建的方法还是你在旧的Rails版本中,但where方法可能是首选。
#app/views/admin/orders/dashboard.html.erb
<%= form_tag(admin_orders_path, method: "get", class: "input-group") do %>
<div class='input-group'>
<%= select_tag :status, options_for_select(['ordered', 'paid', 'completed', 'cancelled']), {prompt: "Select Status", class: "form-control"} %>
<div class='input-group-btn'>
<%= submit_tag "Filter by Status", name: nil, class: 'btn btn-default' %>
</div>
</div>
<% end %>
答案 1 :(得分:0)
对于排序,您可以这样做以稍微干掉您的代码:
# admin_controller.rb
def dashboard
@user = current_user
@all_orders = Order.all
@orders = orders(params[:status])
end
private
def orders(status)
status.present? ? Order.find_status(status) : Order.all
end