Search⌘ K
AI Features

Pagination

Explore how to effectively paginate database results in a Rails API to optimize performance. Learn methods to load data incrementally, handle JSON output properly, comply with JSON API pagination standards, and provide clients with necessary navigation information for paginated resources.

We'll cover the following...

Technically, we could say that the project is now finished, but we want to cover some essential details about optimization. The topics we will discuss in this chapter are the following:

  • Pagination
  • Caching
  • Optimization of SQL queries
  • Activation of CORSCross-Origin Resource Sharing (CORS) is used to allow a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

We will mostly focus on covering some common scenarios. Hopefully, working through these scenarios now will be helpful in some future project.

A strategy to optimize an array of records from the database is to load only a few at a time by paginating them. Pagination is the task of dividing the potential result into pages and retrieving the required pages on demand. In Rails, this is easy to achieve through either will_paginate or kaminari.

The tricky part here is figuring out how to handle the JSON output to give the client enough information on how the array is paginated.

In the format section of https://jsonapi.org, there is a sub-section called pagination. They discuss pagination as follows:

“Pagination links MUST appear in the links object that corresponds to a collection. To paginate the primary data, supply pagination links in the top-level links object.”

This gives us a hint on what to do next about the pagination implementation.

Let’s start with the products list.