DEV Community

Cover image for Rails: Switches Serializer according to STI Type

Posted on

Rails: Switches Serializer according to STI Type


Hello, here is Tamura.

Suppose you have model data of multiple types using STI and want to mix and return them in a single API endpoint. In this case, you would like to switch the serializer according to the STI type.

In this article, I will show you how to do this.


Suppose the following class hierarchy is realized in STI

class hierarchy

SimplePosts has a title and body field, and QAPosts has a question and answer field. They all have a common posted_at field.

Suppose you define an API endpoint called /api/v1/posts and want to return JSON as follows:

return JSON

Depending on whether the Posts type is SimplePost or QAPost, the JSON keys will differ.

If you are using ActiveModel::Serializers to output JSON, you will need to switch the Serializer depending on the type of Posts.


The code is shown below.









Override the attributes method in PostSerializer. Since each data is taken as an object, the class is determined in case, and, reload) and nil, reload) generates attributes and merges them into @attributes.


The reason for overriding the json_key method is to display posts in the json toplevel object. If this is not defined, qa_posts and the type first processed by the Serializer will be set as the key, as shown below.

set as the key

Note that if jsonapi_include_toplevel_object is false, there is no need to override the json_key method.


About Us💡

In addition, I want to introduce a little more about GROWI, an open software developed by us WESEEK, Inc.

GROWI is a wiki service with features-rich support for efficient information storage within the company. It also boasts high security and various authentication methods are available to simplify authentication management, including LDAP/OAuth/SAML.

GROWI originated in Japan and GROWI OSS is FREE for anyone to download and use in English.

For more information, go to to learn more about us. You can also follow our Facebook to see updates about our service.

Top comments (0)