Rails pagination, will_paginate, and AJAX

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

end

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.

https://github.com/ronalchn/ajax_pagination/wiki/Adding-AJAX-to-will_paginate

If you try this, and have any questions or suggestions, feel free to comment and I will help the best I’m able. Thanks!

Advertisements
Tagged , , ,

One thought on “Rails pagination, will_paginate, and AJAX

  1. niuxiufeng says:

    very helpful , thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: