DEV Community

AndyRosenberg
AndyRosenberg

Posted on

Implementing cursor pagination with ActiveRecord

The PaginationService

I had some fun with this one. Implementing pagination almost always gives me a touch of anxiety, especially your typical LIMIT/OFFSET pagination. I had recently discovered the more performant cursor pagination from this post and wanted to give it a go. I created a service in my latest Roda app to be able to take some arguments, chain a query and run the high-performance pagination from there.

I started with implementing a couple different gems, then was able to gather what I needed to create my own version with more control. Parulian's post and repo was a huge inspiration for my service (big thanks!). I needed the returned formatting to be a little more specific and the query chaining capabilities to be a bit more explicit, so I was able to create a base structure around his library and convert the service based on my needs.

Here's a little explanation of the code. We basically have a parent service class (not shown) that converts args passed into an instance into accessors. We use a class method to define defaults, and another to pass in keyword arguments (limited to the accessors listed) to define the boundaries of the query.

PaginationService.paginate defaults to a descending-order page showing the last 25 reviews that were created. The previous and next cursor are returned in the "navigation" pair in the final JSON. What I like about the implementation is that we can pass in an array to the where: option that represents a parameterized query to be chained to the final pagination (i.e. limiting reviews that have a rating higher than 5).

I'm totally nerding out over my own code, but maybe it can help someone that wants to set up their own cursor pagination. Happy trails, devs!

Top comments (0)