简体   繁体   中英

Rails will_paginate: how to keep consistent array index across pages?

I'm using the Rails will_paginate gem with Rails 3.2. I have about 750 movies in my database, and I'm putting them in a table in my view. Here's the 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?' }

I've got default_scope order: 'name ASC' in my movie.rb model to sort them alphabetically, and the each_with_index gives me the ability to have a consistent numerical list of them in the table.

The problem is, now that I'm using pagination, the index of the movie array starts over at every page, so it always just says 1-10.

The question is, how can I make page 1 give say 1-10, then say 11-20 on page 2, etc.?

It seems you may have to modify will_paginate source code to get the page index to work like you intended to (see this SO Post ).

I'll just used a session variable declared in the controller and incremented in my view to get around this.

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

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

[EDITED]
An alternative solution, and thanks to @pjam comment, is to use params[:page] returned by will_paginate. If for example you set :per_page => 5 , your index of current page can be calculated as follow:

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

# View
index + @offset

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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