1
votes

First of all this is with active_model_serializers version 0.10.2 in Rails 4.2.

I have an Article model with two serializers for different scenarios but for this test they are the exact same except for differing class names, ArticleSerializer and ArticleSimpleSerializer. I can't figure out how to get ArticleSimpleSerializer to emit JSON in the JSON API format outside of a controller.

Here's my initializer with global serializer config.

ActiveModelSerializers.config.adapter = :json_api
ActiveModelSerializers.config.jsonapi_resource_type = :singular
ActiveModelSerializers.config.key_transform = :unaltered

What works:

Rendering in a controller: These both output JSON API format with data, type, and attributes root keys. The first one automatically finds and uses ArticleSerializer

render status: :ok, json: @article
render status: :ok, json: @article, serializer: ArticleSimpleSerializer

Rendering outside of controller with default lookup: This will find ArticleSerializer and the output will have data, type, and attributes root keys.

ActiveModelSerializers::SerializableResource.new(article).to_json

What Doesn't Work:

Rendering outside of controller with ArticleSimpleSerializer: This will NOT include data, type, or attributes root keys. The JSON will basically be what I would expect under the attributes key.

ArticleSimpleSerializer.new(article).to_json

How can I get ArticleSimpleSerializer to emil JSON API format outside of a controller?

1

1 Answers

0
votes

You can specify which serializer to use (among other options) with SerializableResource.

This gets me what I wanted.

ActiveModelSerializers::SerializableResource.new(article, serializer: ArticleSimpleSerializer).as_json