will_paginate列表中每个项目的正确数字?(Correct number for each item in will_paginate list?)

我在我的Rails应用程序中使用了will_paginate gem并循环遍历在页面上呈现的模型实例数组,每页限制为5个。 在我添加will_paginate之前,我用简单的<%i + = 1%>编号每个项目,当然每个循环通过数组+1,并且工作正常。

但是现在我正在使用will_paginate,计数会在每个页面重新开始,所以第1页的项目分别为1,2,3,4,5,然后在第二页上重启... 1,2,3,4,五

显然这并不理想。 当您转到上一页时,如何让计数继续?

I'm using the will_paginate gem in my Rails app and loop through an array of model instances which are rendered on the page and limited to 5 per page. Before I added will_paginate I numbered each item with a simple <% i += 1 %> which of course went +1 with each loop through the array, and worked fine.

But now that I'm using will_paginate the count restarts on each page, so page 1 items go 1, 2, 3, 4, 5, and then on the second page it starts over... 1, 2, 3, 4, 5

Obviously this isn't ideal. How do I get the count to continue as you go to previous pages?

最满意答案

will_paginate Collection不仅仅是一个简单的Array或ActiveRecord::Relation 。 相反,它定义了一些其他方法 ,例如: current_page , per_page , offset , total_entries或total_pages 。

您可以使用Collection#offset来计算当前索引:

<% @collection.each_with_index do |item, index| %> <%= @collection.offset + index + 1 %> ... <% end %>

通过使用第一个索引初始化Enumerator#with_index可以简化什么(注意each和with_index之间的. :

<% @collection.each.with_index(@collection.offset + 1) do |item, index| %> <%= index %> ... <% end %>

A will_paginate Collection is not just a simple Array or ActiveRecord::Relation. Instead it has some additional methods defined, for example: current_page, per_page, offset, total_entries or total_pages.

You can use Collection#offset to calculate your current index:

<% @collection.each_with_index do |item, index| %> <%= @collection.offset + index + 1 %> ... <% end %>

What can be simplified by initializing Enumerator#with_index with the first index (note the . between each and with_index:

<% @collection.each.with_index(@collection.offset + 1) do |item, index| %> <%= index %> ... <% end %>

更多推荐