27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

442 CHAPTER 16 Basic performance enhancements<br />

SEEING PAGINATION FOR YOURSELF<br />

Here you’ve seen an easy way to add pagination links to resources in your application<br />

by using the Kaminari gem. You could have used the will_paginate gem and that<br />

would have worked just as easily. It’s really up to personal preference. Pagination<br />

allows you to ease the load on the database server by returning only limited amounts<br />

of records per page, and also doesn’t overwhelm the user with choices.<br />

Let’s see how this works in a browser before you continue. First, you’ll need to create<br />

100 tickets for a project so that you can get two pages of pagination. To do that,<br />

launch rails console and put in this code:<br />

project = Project.first<br />

100.times do |i|<br />

project.tickets.create!(<br />

:title => "Fake ticket",<br />

:description => "Fake description",<br />

:user => User.first<br />

)<br />

end<br />

Next, type exit and press Enter to exit out of the console, and then launch your application<br />

with rails server. You can log in using the email and password you’ve set up<br />

in db/seeds.rb, which are admin@ticketee.com and password, respectively. You can<br />

then click the Ticketee Beta page and you should see a page like figure 16.3.<br />

The pagination here shows that you’re on the first page and that there’s a second<br />

page you can go to, by clicking either the 2 link or the Next link. By clicking this link,<br />

the page switches to the second page of tickets and the URL now becomes http://localhost:3000/projects/1?page=2.<br />

This page parameter is passed to the controller as<br />

params[:page] and then passed to the page method provided by Kaminari.<br />

Figure 16.3 Paginated tickets

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!