Saturday, September 6, 2008

Pagination in rails using will_paginate

Pagination is a technique of presenting large amount of data on the UI, allowing the users to navigate between pages/data in an easy way.
Being a java developer for so many years, I remember doing dirty logic to achieve pagination to using some very useful and advanced tag libraries like displaytag. What ever may be the technique, pagination is never been an easy task.
But when I started playing around with rails and I got a situation where I need to do some pagination. And I readily found a gem will_paginate and doing pagination on rails is a breeze.

Lets get started first by installing the gem.





sudo gem install will_paginate

To check whether the plugin installed successfully or not, you can do the following in your rails console.



1
2
3
defined? WillPaginate
[].paginate
ActiveRecord::Base.respond_to? :paginate


Now lets add pagination support to an imaginary page listing all the clients



1
2
3
  def list_clients
@clients = Client.paginate(:page => params[:page], :per_page => 5)
end
and then render the pagination in the ui using this simple snippet



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<h3>Clients</h3>

<%= will_paginate @clients %>
<!--Loop through all the clients and printem-->
<table width=100% cellpadding=0 cellspacing=0 border=0>
<% for @client in @clients do%>
<tr class='client_details'>
<td align='center'><%=@client.client_name.upcase%><
/
td>
<td>
<%=@client.address_line_1%>,<%=@client.address_line_2%><br />
<%=@client.city%>,<%=@client.state%>,<%=@client.zip%>
<
/
td>
</tr>
<%end%>
<
/
table>


The code <%= will_paginate @clients %> will add the links to previous/next page along with the page numbers to naviage.
The next few lines of code is just to print the client details.

2 comments:

Emeka said...

Great!

maxblacks said...

can you post some screen shots ?