Lets suppose we have articles listing page and we need to show the 10 article per page. So there are we can use 'will_paginate' gem to divide the articles in number of pages.
There are the following steps to integrate the 'will_paginate' gem in our application
Add will_paginate gem in our Gemfile
gem 'will_paginate', '~> 3.0'
Then run command on rails console to install the gem
bundle install
After that we modify the controller for pagination like...
class ArticlesController < ApplicationController
def index
@articles = Article.paginate(:page => params[:page], :per_page => 5)
end
end
page – This is query string parameter decided to which records are to be fetched.
per_page – This is number of record that we want to fetch per page
Modify index.html.erb to display pagination link
%= will_paginate(@articles,:previous_label => "«", :next_label =>"»") %>
previous_label - default: “« Previous”
This params used to display the pagination link for previous label, default link is “« Previous”
next_label - default: “Next »” This params used to display the pagination link for next label, default link is “« Previous”
There are lots of optional params which is passed to HTML attributes for displaying the pagination. If we want to displaying a message containing number of displayed vs. total entries. Add following code after pagination link on the index page .
<%= page_entries_info @article %>
It displaying message like...
Displaying Article 1 - 5 of 7 in total
We can also set per_page params into article.rb model instead of article controller
class Article < ActiveRecord::Base
has_many :comments
validates :title, presence: true, length: { minimum: 5 }
self.per_page = 5
end
And also modify the article controller like...
class ArticlesController < ApplicationController
def index
#@articles = Article.paginate(:page => params[:page], :per_page => 5)
@articles = Article.paginate(:page => params[:page])
end
end
We can also set the per_page params globally using code like
WillPaginate.per_page = 10
0 Comment(s)