与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}
添加了更多元素,则默认kaminari行为{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}
。
我找到了解决方案:
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 = "#{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}
注意:此答案是从另一个Stackoverflow问题交叉发布的。
在github上有一个很好的例子回购在github上叫做reverse_kaminari 。 它建议沿着这些方向实施(来源) 。
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所有。 他还将应用程序托管为工作演示 。
Kaminary.paginate_array
不会生成带偏移量和限制的查询。 出于优化原因,您不应该使用它。
在这里发表我的答案。