Will_paginate on Ajax for Ruby on Rails!

This is a little trick to use the rails plugin “will_paginate” with ajax and classic prototype rails helpers that I used on Kontup. Naturally you should start from here:

http://wiki.github.com/mislav/will_paginate

and follow the classical installation steps. After that you could do in this easy way:

in your controller:

@posts = Post.paginate :page => params[:page]
if params[:page] == nil || params[:page].to_i == 1
@previousPage = nil
@nextPage = 2
else
@previousPage = params[:page].to_i - 1
@nextPage = params[:page].to_i + 1
end

and in your view the links will be:


<% if @previousPage != nil %>
<%= link_to_remote '&laquo; Previous', :url => { :action => "indexAJAX", :page => @previousPage }, :update => "content" %>&nbsp;&nbsp;&nbsp;Page <%= @previousPage %> of <%= @posts.total_pages.to_i %>&nbsp;
<% else %>
Page 1 of <%= @posts.total_pages.to_i %>&nbsp;
<% end %>&nbsp;
<% if @nextPage <= @posts.total_pages.to_i %>
<%= link_to_remote 'Next &raquo;', :url => { :action => "indexAJAX", :page => @nextPage }, :update => "content" %>
<% end %>

I know that there is a smart way to write this code, so please comment here!