How to use ‘will_paginate’ Gem In Ruby
Gems are packages of code in Ruby, similar to libraries or plugins in other programming languages. A Gemfile is a configuration file used in Ruby on Rails applications, to specify the gems and their versions that the project depends on. The file is typically named as ‘Gemfile’. We can implement pagination with ‘will_paginate’ gem, which is quite easier then doing manually.
Follow till Step 5 mentioned in previous method for creating Rails project and example database.
Step 1: Add the ‘will_paginate’ gem to your gemfile using this line. It specifies the gem name and its version.
Run the below command to install the gems.
bundle install
Step 2: Now, edit the ‘app/controllers/posts_controller.rb’ to add the pagination code using the ‘paginate()’ method provided by ‘will_paginate’ gem.
class PostsController < ApplicationController
def index
@posts = Post.paginate(page: params[:page], per_page: 2)
end
end
Step 3: Open ‘app/views/posts/index.html.erb’ and add the below code to display the posts in database on webpage. The button for navigating will be created automatically since we are using ‘will_paginate’ gem.
<% @posts.each do |post| %>
<div>
<h2><%= post.title %></h2>
<p><%= post.content %></p>
</div>
<% end %>
<%= will_paginate @posts %>
Step 4: Edit the ‘config/routes.rb’ to make the index as root page and run the server using ‘rails server’ command.
Rails.application.routes.draw do
root 'posts#index'
end
Output:
How to Implement Pagination in Ruby on Rails?
Pagination in Ruby on Rails is the process of dividing a large amount of material into smaller, easier-to-manage pages or chunks. This is frequently used in web applications to provide data in a more readable style, which enhances the user experience.
Ruby on Rails provides built-in techniques and gems for implementing pagination. ‘will_paginate’ is one of the most widely used gems for pagination, although there are other options as well, such as ‘pagy‘ and ‘kaminari‘.
Table of Content
- Using ‘limit’ and ‘offset’ Methods
- Using ‘will_paginate’ Gem
Contact Us