Rails: pagination with custom offset using Kaminari

梦想与她 提交于 2021-02-19 02:41:05

问题


I'm using Kaminari for pagination and under a certain situation need the first page to contain only 2 entries while each other to have 6. Thought this was achievable using padding(), but it doesn't seem to work like I'd expect (the documentation doesn't help much either):

a = (1..20).to_a
b = Kaminari.paginate_array(a).page(1).per(6).padding(2)
=> [3, 4, 5, 6, 7, 8]

Any ideas on how to accomplish this?


回答1:


this might help you:

a = (1..20).to_a
b = Kaminari.paginate_array(a).page(1).per(6).offset(2)
=> [3, 4, 5, 6, 7, 8]

tested with Kaminari(0.14.1)




回答2:


You can use a negative value for padding, lets say you normally display 6 items per page but for the first page you show only 4. You still setup the per value of 6. Then on pages 2+ you can use a padding of -2 to account for the unused records from page 1.

a = (1..20).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
b = Kaminari.paginate_array(a).page(1).per(6) # Get back 6 but only use 4
=> [1, 2, 3, 4, 5, 6]
c = Kaminari.paginate_array(a).page(2).per(6) # Get the next 6
=> [7, 8, 9, 10, 11, 12]
c.padding(-2) # Correct for the missing 2 on first page
=> [5, 6, 7, 8, 9, 10]

In your controller you would do something like this:

@products = Product.active.page(params[:page]).per(6)
@products = @products.padding(-2) if !params[:page].nil? and params[:page].to_i > 1


来源:https://stackoverflow.com/questions/18239465/rails-pagination-with-custom-offset-using-kaminari

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