Monday, October 3, 2016

Few Tips for Pagination in Rails Apps

Few Tips for Pagination in Rails Apps
When pagination is needed in Rails apps, I always use gem will_paginate. Because it is very simple and just requiring little effort to accomplish my tasks, gem will_paginate become one of my standard gems for every project.
It is simple, but it still need customization to fit my need. For example, the output is not very pretty. The look is not professional.

With Bootstrap Style

What if we use Bootstrap Style to make it a better look? Sure, there is a gem integrates the Twitter Bootstrap pagination component with will_paginate. It is will_paginate-bootstrap.
As usual, add will_paginate-bootstrapin Gemfile:
gem 'will_paginate-bootstrap'
Prepare collection in controller.
def index
  @orders = Order.all.page(params[:page]).per_page(3)
end
Note that the new, shorter page() method is used. It is easier and more intuitive. Then add the line in view template (change @orders to your collection ):
<%= will_paginate(@orders, renderer: BootstrapPagination::Rails %>

Customize the ‘Previous’ and ‘Next’ Tabs

What if we need to replace these two tabs to a simpler way such as ‘<’ and ‘>’?
According to the API documentation, we can assign these options :previous_label and :next_label to the characters we prefer. Therefore, the code becomes:
<%= will_paginate(@orders, 
  renderer: BootstrapPagination::Rails, 
  previous_label: '<', 
  next_label: '>' 
%>
The result:
Bootstrap Pagination

One More Thing: Helper Method

Note that there are many models shown with pagination. The code is duplicated in every view template. Once again, we need code refactoring. I make a helper method generate_pagination in application_helper.rb :
def generate_pagination(object_handled)
  object_paginated = will_paginate(
    object_handled, 
    renderer: BootstrapPagination::Rails,
    previous_label: '<', next_label: '>')
  object_paginated.html_safe if object_paginated
end
Note that the object_paginated is nil (no pagination shown) while there is only one page in the view. A check of object_paginated is necessary for preventing error.
And the view template:
<%= generate_pagination(@orders) %>
That’s it!

No comments:

Post a Comment