【问题标题】:serial number with pagination rails带有分页导轨的序列号
【发布时间】:2013-10-14 20:50:56
【问题描述】:

我正在为我的索引页使用分页,其中列出了所有用户信息,如姓名、电子邮件等。在表格中,我想按 [1,2,3...] 的顺序显示序列号。如果我使用 user_id 并且如果我删除用户,则该数字将不按顺序丢失。我在我的视图中使用以下代码

 <% @user.each_with_index do |d, i| %>

 <tr>

    <td><%= i+1 %></td>
    <% if d.profile.present? %>
   <td><%= link_to d.profile.first_name+ " "+d.profile.last_name, posts_individualpostlink_path(:id => d.id) %> </td>
   <% else %>
    <td><%= "No Profile" %></td>
    <% end %>       
   <td><%= d.email %></td>
   <% if d.profile.present? %>
   <td><%= d.profile.date_of_birth %> </td>
   <% else %>
    <td><%= "No Profile" %></td>
    <% end %>

  </tr>
<% end %>

</table>
 <%= will_paginate @user %>

当我再次进入第二页时,序列号以 [1,2,....] 开头。每页如果我给 10 个用户,第二页应该显示 [11, 12, 13,..... 在表格中。

谁能帮我做这件事。谢谢

【问题讨论】:

    标签: ruby-on-rails pagination


    【解决方案1】:

    试试

    <% 
    count = ((params[:page] || 1).to_i - 1) * 10
    @user.each_with_index do |d, i| %>
    
     <tr>
    
        <td><%= count + i %></td>
    

    【讨论】:

    • 如果我这样做,我会得到系列中的第一个数字为 10,第二页的起始数字为 20。但第一个数字应该是 1。
    • 是的..是的,你需要对 params[:page] 做 -1。请检查我编辑的答案
    【解决方案2】:

    在回答问题之前,请注意一点:停止在您的代码中使用单字母变量。它使它完全不可读。 为什么不使用 &lt;% @user.each_with_index do |user, idx| %&gt; ?现在在 You 代码块中很容易理解 You 总是指用户。

    现在答案。将分页添加页面参数到分页链接。所以在你的控制器中你应该能够做到这一点:

    @page = params[:page] || 1
    

    然后用它来计算你认为正确的数字:

    <td><%= (@page - 1) * number_of_items_on_page + i+1 %></td>
    

    【讨论】:

    • '' 有效。感谢您对单字母变量的建议。我将练习使用可读代码。
    • will_paginate gem 没有提供一些方法或选项吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2016-07-14
    • 1970-01-01
    相关资源
    最近更新 更多