4

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 right order with the right index (palace hast the most visits, then bar, etc.):

  • 1 Palace
  • 2 Bar
  • 3 Cinema
  • 4 Restaurant
  • 5 Ballon

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

  • next page (should continue the index with 6)
  • 1 Arena (should be 6)
  • 2 Stadion (should be 7)
  • and so on ...

So how do I get a persistent counter/index which continues on the next page?

Thanks in advance

Update

I came up with the following, works great 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 %>
  ...
Lukas Hoffmann
  • 607
  • 1
  • 8
  • 21

1 Answers1

1

each_with_index is a plain ruby method (Enumerable I think) that doesn't know anything about the pagination structure. You may have to provide a additional calculation, unless Kaminari provides something (I haven't use Kaminari yet)

If this were will_paginate, I'd do something like this, and maybe it would work for you too:

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

(you have to set @items_per_page yourself)

DGM
  • 26,629
  • 7
  • 58
  • 79