ruby-on-rails - 我怎样才能让分页和排序一起工作
问题描述
我有一些方法可以对表格中的客人列表进行排序并允许用户翻页。他们都单独工作,但我似乎无法让他们一起工作 - 最后一个优先。
我尝试使用 && 和 || 但第一个将只适用。
class GuestlistsController < ApplicationController
before_action :set_guestlist, only: [:show, :edit, :update, :destroy]
helper_method :sort_column, :sort_direction
Guests_Size = 5
def index
@page = (params[:page] || 0).to_i
@guestlists = (Guestlist.offset(Guests_Size * @page).limit(Guests_Size))
@guestlists = (Guestlist.order(sort_column + " " + sort_direction))
respond_to do |format|
format.html
format.csv { send_data @guestlists.to_csv }
format.xls # { send_data @products.to_csv(col_sep: "\t") }
end
end
排序助手
module ApplicationHelper
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, {:sort => column, :direction => direction}, {:class => css_class}
end
end
Guestlist.html.erb 排序
<th scope="col"><%= sortable "firstname" %></th>
<th scope="col"><%= sortable "lastname" %></th>
<th scope="col"><%= sortable "email" %></th>
<th scope="col"><%= sortable "response" %></th>
<th scope="col"><%= sortable "dietary_requirements" %></th>
分页
<ul class="pager">
<li class="previous <%= @page == 0 ? 'disabled' : '' %>">
<%= link_to_if @page > 0, "<< Previous", guestlists_path(page: @page - 1) %>
</li>
<li class="next">
<%= link_to "Next >>", guestlists_path(page: @page + 1) %>
</li>
</ul>
我希望用户进行排序,但也能够在一个页面上一起显示 x 数量的客人。
所发生的只是一个正在发生。
解决方案
这些行中的第二行
@guestlists = (Guestlist.offset(Guests_Size * @page).limit(Guests_Size))
@guestlists = (Guestlist.order(sort_column + " " + sort_direction))
总是覆盖第一行。
只需将您的代码更改为
@guestlists = Guestlist.offset(Guests_Size * @page).limit(Guests_Size)
@guestlists = @guestlist.order(sort_column => sort_direction)
推荐阅读
- r - 将列名移动 10 列
- rust - Adding a closure within a '&self' method to an attribute in a struct
- terminology - What does "to register" mean in terms of programming?
- python - 来自 2 列的 Pandas read_csv parse_dates
- electron - How do I enable Auth0 logins in my Electron app now that Lock v10 is deprecated?
- ruby - 在 Ruby 中创建排序可视化器
- python - Flask - Submit button submits all forms instead of one form
- mule-esb - 在记录之前屏蔽 Mule4 中的敏感数据
- javascript - 脚本只显示一个结果如何输出 ap 标签内的所有结果?
- python - 在 genfromtxt next(fhd) 中,添加新的“带打开文件”行时出现 StopIteration 错误