Active Model Serializer — Custom with Pagy Pagination

Dan Kaplan
2 min readFeb 16, 2021
You got to love Stock Images….

As opposed to just calling render json: @comments, we must specify our response and use this initializer to set our custom serializer.

To take this a step forward and to incorporate pagination with Pagy, we must do the following:

Right now I am rewriting and upgrading an app from a Rails Monolith to a Rails API and a React Front End. For this app, on one page I needed to have a few different calls on the same resource in different forms with pagination. I wanted to be able to easily call my own separate for each call and to have the pagination data be included in the response at the top level.

I have been using Active Model Serializer (v10) to build out JSON responses and up to this point had not run into any cases outside the basics. But in this case, it was difficult to find the correct documentation on how to do this correctly.

To correctly use a custom serializer do the following:

def index
@comments = Comments.all
render json: {
comments:
ActiveModel::Serializer::CollectionSerializer.new(
@comments, serializer: MySpecialCommentSerializer),
}
end

As opposed to just calling `render json: @comments` we must specify our response and use this initializer to set our custom serializer.
To take this a…

--

--