One of the beautiful elements of Ruby on Rails is how much you can do with so few lines of code. The will_paginate gem is a prime example. With just a few line’s of code, you can add pagination to any of your application’s lists. Having dealt with home brewed pagination methods many times during my years as a web developer, I can only say that this little gem has brought me much joy. Below is an example on how to use it.
1) Add the following line of code to your gemfile:
gem 'will_paginate', '~> 3.0'
2) Use the terminal to bundle your gems
$ bundle install
3) Add pagination to your result request code in whatever controller is getting the data to send to the view to create your list. As an example, I am using solr to get a list of indexed books and paginating 15 per page from the list action in my Books controller. Note that the highlighted section is what I added for pagination:
def list per_page = 15 @books = Book.search do keywords(params[:keyword]) paginate :page => params[:page] || 1, :per_page => per_page end @books = @books.results
4) Now, to display a numbered list of pages in your view, all you need to do is add the following code to your view.
<%= will_paginate @books %>
5) Each time you click to move forward or back a page, or you click a page number, the list action will run, receive the appropriate page number in the param[:page] variable, and update your list appropriately.
That’s it, your done! Unless, of course, you would like your list to refresh via ajax. Below is an excellent article detailing the required updates to AJAXify your pagination.
If you try this, and have any questions or suggestions, feel free to comment and I will help the best I’m able. Thanks!