How to Implement Pagination in Rails API in Ruby on Rails
To implement pagination in a Rails API, use the
Kaminari gem to paginate ActiveRecord queries and return limited records per page. Add page and per parameters in your controller to control which records are sent in the JSON response.Syntax
Pagination in Rails API typically uses the Kaminari gem. You call Model.page(params[:page]).per(params[:per_page]) to get the right slice of records. page sets the current page number, and per sets how many records to show per page.
ruby
User.page(params[:page]).per(params[:per_page])
Example
This example shows a Rails API controller action that paginates users. It uses Kaminari to limit results and returns JSON with users and pagination info.
ruby
class Api::UsersController < ApplicationController def index users = User.page(params[:page]).per(params[:per_page] || 10) render json: { users: users, current_page: users.current_page, total_pages: users.total_pages, total_count: users.total_count } end end
Output
{
"users": [
{"id":1,"name":"Alice"},
{"id":2,"name":"Bob"}
],
"current_page": 1,
"total_pages": 5,
"total_count": 50
}
Common Pitfalls
- Not adding
percauses default page size, which may be too large or small. - Forgetting to permit
pageandper_pageparams can cause errors. - Returning only records without pagination metadata makes client handling harder.
- Using offset/limit manually can cause performance issues on large datasets.
ruby
class Api::UsersController < ApplicationController # Wrong: no pagination metadata def index users = User.limit(10).offset((params[:page].to_i - 1) * 10) render json: users end # Right: use Kaminari with metadata def index users = User.page(params[:page]).per(params[:per_page] || 10) render json: { users: users, current_page: users.current_page, total_pages: users.total_pages, total_count: users.total_count } end end
Quick Reference
Use these tips for smooth pagination in Rails API:
- Install
kaminarigem and runbundle install. - Call
Model.page(params[:page]).per(params[:per_page])in controller. - Return pagination info like
current_page,total_pages, andtotal_countin JSON. - Set default
per_pageto avoid too many records. - Validate
pageandper_pageparams to prevent errors.
Key Takeaways
Use the Kaminari gem to paginate ActiveRecord queries easily in Rails API.
Control pagination with
page and per parameters from the request.Always include pagination metadata in the JSON response for client-side navigation.
Set sensible defaults for
per_page to avoid performance issues.Avoid manual offset/limit without metadata as it complicates client handling.