简体   繁体   中英

How to Use Rails will_paginate gem to Divide a Large Table for Print on a Single Page

I am making some printable tables for a client with a Ruby on Rails 3.1 app and need to repeat table headers on each page. Unfortunately, at the moment, WebKit browsers do not support a CSS-based solution.

To solve this issue, I thought I would use the will_paginate gem.

Controller

def
  @books = current_library.books.order('books.title ASC')
end

Current View Code

<% @books.each do |b| %>
<table>
  <thead><th><%= b.title %></th></thead>
  <tbody>  
  <% b.chapters.each do |chap| %
      <td><%= chap.number %> ... <%= chap.name %></td>
  <% end %>
  </tbody>
</table>
<% end %>

How do I setup the pages and step through each one? In other words, how do I get all the pages of the pagination on one view page?

Alternatively, is there a better approach I should pursue?

You might be better off using Enumerable#each_slice here. It allows you to split a large enumerable object into a series of smaller slices, and then iterate on those slices. It's quite nice for this sort of thing, doesn't require any extra math in your loops, and doesn't require a gem.

Here's an example for a collection with 10 items on a page:

<% @books.each_slice(10) do |slice| %>
  <h1>Header Information</h1>
  <h2>Awesome</h2>

  <% slice.each do |book| %>
    <table>
      <thead><tr><th><%= book.title %></th></tr></thead>
      <tbody>  
      <% book.chapters.each do |chap| %
          <tr><td><%= chap.number %> ... <%= chap.name %></td></tr>
      <% end %>
      </tbody>
    </table>
  <% end %>

  <p>Some footer information</p>
<% end %>

This approach will only work if you assume that each book record takes about the same amount of space (so you don't end up with oversized or undersized pages), but that would be a problem with will_paginate as well.

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