JSON API loading style in Rails ActiveModel :: Serializers

I am trying to create a JSON style API using AM :: Serializer. I encountered a problem while loading.

I want to be able to create JSON that looks like this:

{ "primaries": [{ "id": 123, "data": "Hello world.", "links": { "secondaries": [ 1, 2, 3 ] } }], "linked" : { "secondaries": [ { "id": 1, "data": "test1" }, { "id": 2, "data": "test2" }, { "id": 3, "data": "test3" } ] } } 

The code I could find looks like this:

 class PrimarySerializer < ActiveModel::Serializer attributes :id, :data has_many :secondaries, key: :secondaries, root: :secondaries embed :ids, include: true end 

What generates JSON that looks like this:

 { "primaries": [{ "id": 123, "data": "Hello world.", "secondaries": [ 1, 2, 3 ] }], "secondaries": [ { "id": 1, "data": "test1" }, { "id": 2, "data": "test2" }, { "id": 3, "data": "test3" } ] } 

Is there a way to redefine the location of in-element secondaries and sideloaded secondaries so that they are in the link and linked child nodes?

The above code is an abstraction of the actual code and may not work. I hope he illustrates this point quite well.

Thanks!

+6
source share
1 answer

ActiveModel serializers can do this. The problem is that inline union methods are restrictive. Instead, you must manually create the links and linked parts.

(This answer applies to stable version 1.5.1 ActiveModel Serializers )

Here's a Gist with a full JSON-API solution https://gist.github.com/mars/97a637560109b8ddfb27

Example:

 class ExampleSerializer < JsonApiSerializer # see Gist for superclass attributes :id, :name, :links def links { things: object.things.map(&:id), whatzits: object.whatzits.map(&:id) } end def as_json(*args) hash = super(*args) hash[:linked] = { things: ActiveModel::ArraySerializer.new( object.things, each_serializer: ThingsSerializer ).as_json, whatzits: ActiveModel::ArraySerializer.new( object.whatzits, each_serializer: WhatzitsSerializer ).as_json } hash end end 
+2
source

All Articles