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💡
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. You can also follow our Facebook to see updates about our service.
Top comments (0)