Rails: Switches Serializer according to STI Type
Introduction
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.
Issue
Suppose the following class hierarchy is realized in STI
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:
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.
Solution
The code is shown below.
app/serializers/post_serializer.rb
app/serializers/simple_post_serializer.rb
app/serializers/qa_post_serializer.rb
app/controllers/api/v1/posts_controller.rb
Override the attributes
method in PostSerializer. Since each data is taken as an object
, the class is determined in case, and SimplePostSerializer.new(object).attributes(nil,reload)
and QAPostSerializer.new(object).attributes(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.
Note that if jsonapi_include_toplevel_object
is false
, there is no need to override the json_key
method.
About Us💡
GROWI
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 GROWI.org to learn more about us.
GROWI.cloud
GROWI.cloud is the online version of GROWI that allows non-engineers to manage knowledge easily without system-building processes.
Besides organizational use, GROWI.cloud is also available for individual use and you can always start with a free trial here. After the one-month free trial, you can change your plan into either the individual, duo, or trio plan, OR continue to use the personal plan for FREE with a maximum of 25 users! Go to price & features to learn about the details.
GROWI.cloud origins in Japan and now also offered in the Philippine and other countries which allows customers to use the service in English.
Go to GROWI.cloud to learn more about us. You can also follow our Facebook to see updates about our service.