How to Implement Pagination in Ruby on Rails?
Last Updated :
08 May, 2024
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'.
Using 'limit' and 'offset' Methods
You can implement pagination in Ruby on Rails manually without using methods like 'will_paginate'. Active Record is an ORM(Object-Relational Mapping) library that provides a set of methods and techniques to interact with databases using classes. We can use the 'limit' and 'offset' methods provided by Active Record.
Step 1: Create a demo project using the command below. It will create a project named 'railsapp' in the current directory. Then use the second command to get into your project directory.
rails new railsapp
cd railsapp
Create an appStep 2: Now, we will create a controller and view using the following command. This command creates a controller file named 'posts_controller.rb' in ‘app/controllers’ and its view file 'index.html.erb' in ‘app/views/home’. This command also creates a route file 'config/routes.rb'.
rails generate controller Posts index
Generate controller and viewStep 3: Next, we will create a 'Post' model which will have attributes as 'title' and 'content'.
rails generate model Post title:string content:text
Create a modelStep 4: We will run the migration to create the table in our database. Run the following command in terminal. This will execute the migration file and create a posts table in our database with columns for title and content.
rails db:migrate
Run migration fileStep 5: Open 'db/seeds.rb' and fill example data. This code will create 5 posts with title and content.
Ruby
# Generate example posts
5.times do |i|
Post.create(title: "GeeksforGeeks Post #{i+1}", content: "This is content for post #{i+1}")
end
Then run this command in terminal.
rails db:seed
Step 6: Now, we will implement pagination, for that open 'app/controllers/posts_controller.rb' and write the below code.
Ruby
class PostsController < ApplicationController
def index
page = params[:page].to_i || 1
@per_page = 2 # Number of records per page
offset = (page - 1) * @per_page
@posts = Post.limit(@per_page).offset(offset)
end
end
Explanation:
- In this code, the first line retrieves the current page number from the URL parameters.
- It converts the page number to an integer using '.to_i'.
- If the page parameter is not present or evaluates to nil, it defaults to 1.
- Then we have defined that there will be 2 posts/records per page.
- The offset method determines how many posts to skip in the database query based on the current page number and the number of records per page.
- For example, on second page offset = (2 - 1) * 2 = 2, so the first two post will be skipped, since they already fetched on first page.
Step 7: Open 'app/views/posts/index.html.erb' and write the below code. It will display the content from database and creates Previous and Next buttons using 'link_to' method.
HTML
<% @posts.each do |post| %>
<div>
<h2><%= post.title %></h2>
<p><%= post.content %></p>
</div>
<% end %>
<% if params[:page].to_i > 1 %>
<%= link_to "Previous", root_path(page: params[:page].to_i - 1) %>
<% end %>
<% if @posts.size == @per_page %>
<%= link_to "Next", root_path(page: params[:page].to_i + 1) %>
<% end %>
Step 8: Now, set the index page as root by changing the 'config/routes.rb' as mentioned below in code.
Ruby
Rails.application.routes.draw do
root 'posts#index'
end
Now, run the server using this command in terminal.
rails server
Output:
Pagination outputUsing 'will_paginate' Gem
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.
Add gem to GemfileRun the below command to install the gems.
bundle install
Install gemStep 2: Now, edit the 'app/controllers/posts_controller.rb' to add the pagination code using the 'paginate()' method provided by 'will_paginate' gem.
Ruby
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.
HTML
<% @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.
Ruby
Rails.application.routes.draw do
root 'posts#index'
end
Output:
will_paginate output
Similar Reads
How to implement pagination in React Redux Applications?
Pagination is a common requirement in web applications. It is very helpful when we wish to display or manage a large dataset on the website in an aesthetic manner. Whenever it comes to displaying a large number of data, state handling comes into the picture. The idea of pagination has a good binding
5 min read
How to Add Image in Ruby on Rails?
In Ruby on Rails, there are several ways to add images to your application. In this article, we will see one of the common methods which is using an assets pipeline. Steps on How to Create a ProjectStep 1: Create a demo project using the command below. It will create a project named 'myapp' in the c
2 min read
Implementing Pagination in MySQL Queries with Go
Pagination is an important method in web applications and APIs in the task of working with extensive data. Pagination reveals data in reasonable portions instead of a complete set because the later consumes time, slows website functionality, and may present numerous records to the user. This makes t
6 min read
How to Install Ruby on Rails on MacOS?
Ruby on Rails, also known as rails, is a server-side web application development framework written in the Ruby programming language. David Heinemeier Hansson developed it under the MIT License. It supports MVC (model-view-controller) architecture that provides a default structure for databases, web
2 min read
How to Add Pagination in HTML Table ?
Pagination is a common feature in web applications, especially when dealing with large datasets. It helps in dividing the data into manageable chunks, improving the user experience by reducing the amount of data displayed at once and speeding up page loading times. In this article, we will discuss t
3 min read
How to Pagination in PL/SQL?
Pagination is a technique used to divide large datasets into smaller, manageable chunks called pages. It's important for improving user experience and optimizing database performance. In PL/SQL, pagination can be achieved using various methods, allowing users to navigate through query results effici
5 min read
How to Install Ruby on Rails on Windows and Linux?
Ruby on Rails or just known as rails, is free and open-source software written in Ruby language under the MIT license. It is a server-side web application development framework, designed to make programming web applications easier by making assumptions about what every developer needs to get started
2 min read
How to create model in Ruby on Rails?
In Ruby on Rails, models are like the organizers of your data. They handle interactions with your database. Think of them as the brains of your application, responsible for managing and manipulating data. They represent the structure and behavior of the information your app works with. So, whenever
4 min read
How to create API in Ruby on Rails?
Building APIs with Ruby on Rails: A Step-by-Step GuideRuby on Rails (Rails) is a popular framework for web development, known for its convention over configuration approach. It also excels in creating robust and maintainable APIs (Application Programming Interfaces). APIs act as intermediaries, allo
3 min read
How to Create Button in Ruby on Rails?
Ruby on Rails, commonly known as Rails, is a popular web application framework written in the Ruby programming language. It follows the Model-View-Controller (MVC) architectural pattern, which separates the application's data, logic, and user interface components. Rails emphasizes convention over co
7 min read