How to use ‘limit’ and ‘offset’ Methods In Ruby
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
Step 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
Step 3: Next, we will create a ‘Post’ model which will have attributes as ‘title’ and ‘content’.
rails generate model Post title:string content:text
Step 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
Step 5: Open ‘db/seeds.rb’ and fill example data. This code will create 5 posts with title and content.
# Generate example posts
5.times do |i|
Post.create(title: "w3wiki 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.
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.
<% @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.
Rails.application.routes.draw do
root 'posts#index'
end
Now, run the server using this command in terminal.
rails server
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