加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby / Rails中的持久计数器

发布时间:2020-12-17 01:59:25 所属栏目:百科 来源:网络整理
导读:我有以下代码,它为我提供了一堆位置和每个位置的索引. %= paginate @locations %% @locations.each_with_index do |location,index| % h1%= index + 1 %/h1 h2%= location.name %/h2% end % 一切正常,我用正确的索引得到正确顺序的所有元素(宫殿有最多的访问
我有以下代码,它为我提供了一堆位置和每个位置的索引.

<%= paginate @locations %>

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

一切正常,我用正确的索引得到正确顺序的所有元素(宫殿有最多的访问,然后是酒吧等):

> 1宫
> 2吧
> 3电影院
> 4餐厅
> 5 Ballon

我使用Kaminari进行分页,如果我点击第二页显示接下来的5个位置,索引会再次从1开始,但它应该给我6.

>下一页(应该用6继续索引)
> 1竞技场(应为6)
> 2 Stadion(应为7)
>依此类推……

那么如何在下一页继续获得持久的计数器/索引呢?

提前致谢

更新

我想出了以下内容,到目前为止效果很好:

<% 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 %>
  ...

解决方法

each_with_index是一个普通的ruby方法(我认为是Enumerable),它对分页结构一无所知.您可能需要提供额外的计算,除非Kaminari提供某些东西(我还没有使用Kaminari)

如果这是will_paginate,我会做这样的事情,也许这对你也有用:

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

(你必须自己设置@items_per_page)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读