Paginate Results

This guide shows you how to paginate query results for display in pages.

Basic Pagination

Use limit and offset:

page = 1
per_page = 10

posts = Post.order(created_at: :desc)
            .limit(per_page)
            .offset((page - 1) * per_page)
            .all

Pagination Helper

Create a reusable pagination method:

def paginate(query, page : Int32 = 1, per_page : Int32 = 10)
  offset = (page - 1) * per_page
  query.limit(per_page).offset(offset).all
end

# Usage
posts = paginate(Post.where(published: true), page: 2, per_page: 20)

Pagination Info

Get total count for pagination UI:

Cursor-Based Pagination

For better performance with large datasets:

Timestamp-Based Pagination

For chronological data:

Keyset Pagination

More efficient for large datasets:

Web API Example

Verify Pagination Works

Last updated

Was this helpful?