Pagination in Rails Application:

Kaminari and will_paginate are the mostly used and the best gems for pagination.

Also if you want to go for pagination on scroll with link for ex. “Load More Result”

(as we have for activities in knowbuddy), then it is also easy with this gems.

You can check this tutorial(Tutorial)

Pagination with infinite scrolling:

But if you want to have pagination as we have in facebook, without any load-more link, just display result as we scroll down through the page, then here you can make use of this plugin jquery.pageless [Github link(Github Doc.)][2]

Here you just need to bind the event with the class of div

Steps:

  1. Download the js file [here(JS File)][3] and include it in your application.js file
//= require jquery.pageless
  1. Suppose we want to display user activities.

Controller:

def activities
  @activities = PublicActivity::Activity.order('created_at DESC').page(params[:page]).per(10)
  @complete_status = @activities.count == 10 ? false : true
  render layout: false  if request.xhr?
end

View:

.activities
  - @activities.each do |activity|
    / display activity text

// Pageless Initialization
:javascript
  function stop_pageless() {
    $('.activities #pageless-loader').hide();
    $('.activities').unbind('scroll');
    $(window).unbind('scroll');
  };

  function hide_spinner() {
    $('.activities #pageless-loader').hide();
  };

  - unless @complete_status
    :javascript
      $('.activities').pageless({ totalPages: 100
        , url: "/activities"
        , loader: "#loading_spinner"
        , loaderImage: "/assets/loading_spinner.gif"
        , loaderMsg: 'Loading more results'
        , distance: 350
        , complete: hide_spinner()
      });

  - else
    :javascript
      stop_pageless()

Issues:

The main issue with this plugin is, the loading status displayed continuously, even though we reached last page i.e. after all records are displayed.

So to stop ajax call, we need add check which will unbind the event called for scroll once all records are displayed.

In above code snippet, if @complete_status is true, it would hide spinner and unbind scroll event.

There might be other plugins and gems for the infinite scroll, but if you are going to use this then make sure to add this check.

[2]: https://github.com/jney/jquery.pageless)
[3]: https://github.com/jney/jquery.pageless/blob/master/lib/jquery.pageless.js