Agile Web Development with Rails

Page 122

H ELPERS

FOR

F ORMATTING , L INKING ,

AND

P AGINATION

page. If a request comes in with page=1, the proxy returns the first thirty users in the table. If page=2, the 31st through 60th users are returned. Alternately, you can use the :per_page option to specify a different number of records per page.

Over in the view file user_list.html.erb, we display the users using a conventional loop, iterating over the @users collection created by the paginator. We use the pagination_links helper method to construct a nice set of links to other pages. By default, these links show the two page numbers on either side of the current page, along with the first and last page numbers. Download e1/views/app/views/pager/user_list.html.erb

<table> <tr><th>Name</th></tr> <% for user in @users %> <tr><td><%= user.name %></td></tr> <% end %> </table> <hr/> <%= will_paginate @users <hr/>

%>

Navigate to the user_list action, and you’ll see the first page of names. Click the number 2 in the pagination links at the bottom, and the second page will appear.

Pagination is not a complete solution for breaking up the display of large sets of data. Although it is often useful, as you become more experienced with Rails, you may well find yourself rolling your own. You can find more information on the will_paginate gem at http://github.com/ mislav/will_paginate/wikis. Report erratum

Prepared exclusively for Bill Trammel

this copy is (P1.0 printing, March 2009)

522


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.