与kaminari反向分页?

时间:2013-01-27 13:45:28

标签: ruby-on-rails kaminari

我正在使用Kaminari 0.13.0和RubyOnRails 3.2.8。

假设我在crated_at之前对我的元素进行了默认排序,我的列表8中有{a, b, c, d, e, f, g, h}个元素,并且每页为3分页。

默认情况下,kaminari会创建以下页面链接1, 2, 3链接到{h, g}{f, e, d}{c, b, a}

如何让kaminari以相反的顺序创建页面链接?我希望它以相反的顺序生成链接3, 2, 1仍然链接到反向排序的元素{h, g}{f, e, d}{c, b, a}

关于我要解决的问题的一点背景:

我通过created_at命令页面上的元素。我希望元素永远保持在同一页面上。如果我不使用反向分页,每次添加新元素时,页面内容都会发生变化。因此,在上面的示例中,如果我向列表{i, j}添加了更多元素,那么1st页面会包含{j, i, h},而不是{h, g}2nd页面将包含{g, f, e}而不是{f, e, d},以及... 这对博彩,搜索引擎优化等不利。

如果我有上述的反向页面编号,那么1st页面仍会有{c, b, a}3rd页面将使用新元素更新为{i, h, g}并且会有一个新的第4页,其中包含一个元素{j}

3 个答案:

答案 0 :(得分:1)

我找到了解决方案:

def index
  users_scope = Users.order(:whateva)
  @users = reverse_paginate(users_scope, params[:page])
end

def reverse_paginate(scope, page)
  if page
    page_number = page
  else 
    page_number = Kaminari.paginate_array(scope.reverse).page(1).per(10).num_pages
  end
  Kaminari.paginate_array(scope.reverse).page(page_number).per(10).reverse!
end

您需要更新kaminari页面视图_page.html.erb并将?page=1添加到网址:

   url = "#{url}?page=1" if page.number == 1
   link_to_unless page.current?, page.number, url, opts = {:remote => remote, :rel => page.next? ? 'next' : page.prev? ? 'prev' : nil}

答案 1 :(得分:0)

注意:此答案是从another Stackoverflow question交叉发布的。

在Github上有一个很好的例子回购在github上叫reverse_kaminari。它建议沿着这些方向实施(Source)

class CitiesController < ApplicationController

  def index
    @cities = prepare_cities City.order('created_at DESC')
  end

  private

  def prepare_cities(scope)
    @per_page = City.default_per_page
    total_count = scope.count
    rest_count = total_count > @per_page ? (total_count % @per_page) : 0
    @num_pages = total_count > @per_page ? (total_count / @per_page) : 1

    if params[:page]
      offset = params[:page].sub(/-.*/, '').to_i
      current_page = @num_pages - (offset - 1) / @per_page
      scope.page(current_page).per(@per_page).padding(rest_count)
    else
      scope.page(1).per(@per_page + rest_count)
    end
  end

end

所有积分都转到Andrew Djoga。他还将应用程序托管为a working demo

答案 2 :(得分:0)

Kaminary.paginate_array不会产生带偏移和限制的查询。出于优化原因,您不应该使用它。

发表我的回答here