How to set different page size for the first page in Kaminari?

只谈情不闲聊 提交于 2019-12-10 09:25:03

问题


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.

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...

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 is the current 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}, etc...

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} etc...
The offset method also does not set the current_page correctly, so this does not seem like the correct method.

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?


回答1:


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.

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.




回答2:


Buddy, I've found the way of get it working using padding:

@page = (params[:page] || '1').to_i
@per_page = 4
if @page == "1"
  Alphabet.page(@page).per(@per_page - 1)
else
  Alphabet.page(@page).per(@per_page).padding(-1)
end

This way, first page will return 3 items and the other pages 4 items.



来源:https://stackoverflow.com/questions/18489398/how-to-set-different-page-size-for-the-first-page-in-kaminari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!