用kaminari反向分页 [英] Reverse pagination with kaminari

查看:78
本文介绍了用kaminari反向分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为消息传递系统创建分页,其中显示的第一页包含最旧的消息,随后的页面显示较新的消息.

I want to create pagination for a messaging system in which the first page shown contains the oldest messages, with subsequent pages showing newer messages.

例如,如果{a,b,c,d,e,f,g,h,i}的常规分页为每页3个,则为:

For example, if normal pagination for {a,b,c,d,e,f,g,h,i} with 3 per page is:

{a,b,c}, {d,e,f}, {g,h,i}

那么反向分页将是:

{g,h,i}, {d,e,f}, {a,b,c}

我打算将页面放在前面,以便结果与普通分页相同,只是从最后一页开始.

I plan to prepend the pages so the result is the same as normal pagination, only starting from the last page.

kaminari可能吗?

推荐答案

在Github上有一个很好的示例存储库,名为 reverse_kaminari 在github上.它建议按照以下方式实现:(源).

There's a good example repo on Github called reverse_kaminari on github. It suggests an implementation along these lines (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 .他还以正在运行的演示的身份托管了该应用.

All credits go to Andrew Djoga. He also hosted the app as a working demo.

这篇关于用kaminari反向分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆