首页 > 解决方案 > 我怎样才能让分页和排序一起工作

问题描述

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

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

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 数量的客人。

所发生的只是一个正在发生。

标签: ruby-on-railsrubysortingpaginationruby-on-rails-5

解决方案


这些行中的第二行

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

推荐阅读