如何进行分页和排序

时间:2019-10-05 14:07:05

标签: ruby-on-rails ruby sorting pagination ruby-on-rails-5

我有一些方法可以对表进行排序,并允许用户在表的来宾列表中进行分页。他们俩都单独工作,但我似乎无法让他们一起工作-最后一个优先。

我尝试使用&&和||但第一个仅适用。

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位访客。

发生的事情只有一个正在发生。

1 个答案:

答案 0 :(得分:0)

其中第二行

@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)