如何在 Kaminari 中为第一页设置不同的页面大小? [英] How to set different page size for the first page in Kaminari?

查看:41
本文介绍了如何在 Kaminari 中为第一页设置不同的页面大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多对象想要使用 Kaminari 进行分页.但是,在第一页上,我还想显示一个通知,允许查看者创建自己的对象,从而减少该页面上可以显示的对象数量.但是,指示的页数还应考虑到第一页包含的元素较少.

I have a number of objects I would like to paginate using Kaminari. However, on the first page I would also like to show a notification allowing the viewer to create his own object, reducing the number of objects that can be displayed on that page. However, the indicated number of pages should also take into account that this first page contains less elements.

假设对象是字母 a 到 z.第一页应该只显示 4 个字母:{a,b,c,d},而所有其他页面应该显示 6 个字母:{e,f,g,h,i,j}, {k,l,m,n,o,p} 等...

Let's say the objects are the letters a through z. The first page should only 4 display letters: {a,b,c,d}, while all other pages should show 6 letters: {e,f,g,h,i,j}, {k,l,m,n,o,p}, etc...

我一直在研究 paddingoffset 函数,但我还没有能够用这些产生想要的结果.

I've been looking at the padding and offset functions, but I have not yet been able to produce the wanted results with these.

@page 是当前页面

if @page == 1
  Alphabet.page(@page).per(4)
else
  Alphabet.page(@page).per(6).padding(2)
end

<代码>=>{a,b,c,d},{i,j,k,l,m,n} 等...

if @page == 1
  Alphabet.page(@page).per(4)
else
  Alphabet.page(@page).per(6).offset(4)
end

<代码>=>{a,b,c,d},{e,f,g,h,i,j}, {e,f,g,h,i,j} 等...
offset方法也没有正确设置current_page,所以这似乎不是正确的方法.

=> {a,b,c,d},{e,f,g,h,i,j}, {e,f,g,h,i,j} etc...
The offset method also does not set the current_page correctly, so this does not seem like the correct method.

我怎样才能得到看起来像 {a,b,c,d}, {e,f,g,h,i,j}, {k,l,m,n,o,p 的分页} 等...,同时还在第一页上显示正确的页数,在本例中为 5?

How can I get pagination that looks like {a,b,c,d}, {e,f,g,h,i,j}, {k,l,m,n,o,p}, etc..., while also displaying the correct number of pages on the first page, in this case 5?

推荐答案

在互联网上进行了更多挖掘后,我在 'Kaminari recipes' 关于数组分页,使用 Ruby 的 instance_eval 方法手动分页一个数组.

After some more digging on the internet, I found an interesting segment in 'Kaminari recipes' about paginating arrays, that used Ruby's instance_eval method to manually paginate an array.

我自己尝试使用这个 instance_eval,看起来这似乎有效,虽然它看起来很hacky

I tried using this instance_eval myself, and it seems that this seems to work, although it looks rather hacky

@page = (params[:page] || '1').to_i

if @page == 1
  @alphabet = Alphabet.recent.limit(4)
else
  @alphabet = Alphabet.recent.limit(6).offset(@page*6-8)
end

@alphabet.instance_eval <<-EVAL
  def current_page
    #{@page}
  end
  def total_pages
    ((Alphabet.all.count+2)/6.0).ceil
  end
EVAL

我确信有一些更好的方法,但由于现在这似乎可以解决问题,我将保持原样.

I'm sure there is some better way out there, but since this seems to do the trick for now, I will leave it as is.

这篇关于如何在 Kaminari 中为第一页设置不同的页面大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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