Rails will_paginate:如何在页面之间保持一致的数组索引?

时间:2013-01-07 00:22:01

标签: ruby-on-rails haml will-paginate

我在Rails 3.2中使用Rails will_paginate gem。我的数据库中有大约750部电影,我将它们放在一张桌子中。这是haml:

%h1 Listing movies
%table.table.table-striped
  %tr
    %th No.
    %th Name
    %th Rating
    %th
  - @movies.each_with_index do |movie, index|
    %tr
      %td= (index + 1) 
      %td= link_to movie.name, edit_movie_path(movie)
      %td= movie.rating
      %td= link_to 'Delete', movie, method: :delete, data: { confirm: 'Are you sure?' }

我的default_scope order: 'name ASC'模型中有movie.rb按字母顺序排序,each_with_index使我能够在表格中找到一致的数字列表。

问题是,现在我正在使用分页,电影数组的index从每个页面开始,所以它总是只用1-10表示。

问题是,如何让第1页给1-10说,然后在第2页说11-20等?

1 个答案:

答案 0 :(得分:1)

似乎您可能需要修改will_paginate源代码以使页面索引按预期工作(请参阅this SO Post)。

我将使用在控制器中声明的会话变量,并在我的视图中递增以解决此问题。

session[:index] ||= 0
if params[:search]
   session[:index] = 0
end

# View
<% session[:index] = session[:index] + 1 %>

<强> [EDITED]
另一种解决方案,感谢@pjam评论,是由will_paginate返回的use params[:page]。例如,如果设置:per_page => 5,则可以按以下方式计算当前页面的索引:

@offset = (params[:page] - 1) * params[:per_page] + 1

# View
index + @offset
相关问题