tommers
tommers

Reputation: 51

Render partial with collection and display counter for each object with Pagy Gem

I want to display the index of each record in a collection when it's rendered in my rails app.

For example: Name, 1 Name, 2 Name, 3. ....

I use the built-in hidden index to accomplish this today, but after adding pagination with the Pagy gem the index restarts every time I go to a new page. So if I display 20 records per page, the first index on page 2 should be 21, but it currently displays 1.

Heres' my code:

teams_controller.rb

def index
if params[:query]
  @pagy, @teams = pagy(Team.includes(:stadium).global_search(params[:query]))
else
  @pagy, @teams = pagy(Team.order_by_score)
end
end

index.html.erb

<%= render partial: "teams/card", collection: @teams, as: 'team' %>

in my partial.html.erb

<%= team_counter +1   %>

Any idea on how I can display the index of each record without it having to restart on each page?

Anything that could help me would be greatly appreciated.

Upvotes: 0

Views: 845

Answers (1)

spickermann
spickermann

Reputation: 107077

@pagy.offset returns the offset of the current page which you can pass to with_index to calculate the correct index of a record.

<% @teams.each.with_index(@pagy.offset) do |team, index| %>
  <%= render partial: "teams/card", team: team, index: index %>
<% end %>

and show the index in your teams/card partial like this:

<%= index %>

When you want your index to start from 1 instead of 0 just change with_index(@pagy.offset) to with_index(@pagy.offset + 1) in the above example.

Upvotes: 2

Related Questions