简体   繁体   English

使用 Pagy Gem 为每个 object 使用收集和显示计数器渲染部分

[英]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.我想在我的 rails 应用程序中呈现集合中的每条记录时显示它的索引。

For example: Name, 1 Name, 2 Name, 3. ....例如:姓名、1 姓名、2 姓名、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.我今天使用内置的隐藏索引来完成此操作,但是在使用 Pagy gem 添加分页后,每次我 go 到新页面时,索引都会重新启动。 So if I display 20 records per page, the first index on page 2 should be 21, but it currently displays 1.因此,如果我每页显示 20 条记录,则第 2 页上的第一个索引应该是 21,但它当前显示的是 1。

Heres' my code:这是我的代码:

teams_controller.rb团队控制器.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索引.html.erb

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

in my partial.html.erb在我的部分.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.任何可以帮助我的东西都将不胜感激。

@pagy.offset returns the offset of the current page which you can pass to with_index to calculate the correct index of a record. @pagy.offset返回当前页面的偏移量,您可以将其传递给with_index以计算记录的正确索引。

<% @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:并在您的teams/card部分中显示索引,如下所示:

<%= 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.当您希望索引从1而不是0开始时,只需在上面的示例中将with_index(@pagy.offset)更改为with_index(@pagy.offset + 1)

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

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