简体   繁体   English

Rails:使用 Kaminari 使用自定义偏移量进行分页

[英]Rails: pagination with custom offset using Kaminari

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):我正在使用 Kaminari 进行分页,在某种情况下需要第一页只包含 2 个条目,而彼此有 6 个条目。认为这是可以使用padding()实现的,但它似乎不像我期望的那样工作(文档也没有多大帮助):

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?关于如何实现这一点的任何想法?

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)用 Kaminari(0.14.1) 测试

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.您可以为填充使用负值,假设您通常每页显示 6 个项目,但对于第一页,您只显示 4 个。您仍然将每个值设置为 6。然后在页面 2+ 上,您可以使用 -2 的填充考虑第 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM