Ruby / Rails permanent counter for each

I have the following code that gives me a bunch of locations and an index for each location.

<%= paginate @locations %> <% @locations.each_with_index do |location, index| %> <h1><%= index + 1 %></h1> <h2><%= location.name %></h2> <% end %> 

Everything works fine, I get all the elements in the correct order with the correct index (the palace has the most visits, then the bar, etc.):

  • 1 Palace
  • 2 bar
  • 3 Cinema
  • 4 Restaurant
  • 5 Cylinder

I use Kaminari for pagination, and if I go to the second page to show the next 5 locations, the index starts at 1 again, but it should give me 6.

  • next page (index should be continued from 6)
  • 1 Arena (should be 6)
  • 2 Stadion (should be 7)
  • etc.

So, how do I get a constant counter / index that continues on the next page?

Thank you in advance

Update

I came up with the following, works fine so far:

 <% if params[:page].nil? || params[:page] == "0" || params[:page] == "1" %> <% x = 0 %> <% else %> <% page = params[:page].to_i - 1 %> <% x = page * 10 %> <% end %> <% @locations.each_with_index do |location, index| %> <%= index + x + 1 %> ... 
+4
source share
1 answer

each_with_index is a simple ruby ​​method (enumerated, I think) that knows nothing about the structure of pagination. You may need to provide an additional calculation unless Kaminari provides something (I have not used Kaminari yet)

If it was_paginate, I would do something like this, and maybe this will work for you too:

 <h1><%= index + 1 + ((params[:page] || 0 ) * @items_per_page ) %></h1> 

(you must set @items_per_page yourself)

+1
source

All Articles