Search code examples
ruby-on-rails-5active-model-serializers

How to group Associations' attributes in a Collection (Active Model Serializer)


Consider the below two entities: Posts, Authors

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, author_id
  belongs_to :author
end

Class AuthorSerializer < ActiveModel::Serializer
  attributes :id, :name
end

Using the 'JSON' adapter, for the index action of PostsController we get the response as below:

{
  "posts":[
    {
      "id":1,
      "title":"Hic consectetur et delectus",
      "author_id": 1,
      "author":{"id":1,"name":"Author-A"}
    },
    {
      "id":2,
      "title":"Hic consectetur et delectus",
      "author_id": 2,
      "author":{"id":2,"name":"Author-B"}
    },
    {
      "id":3,
      "title":"Hic consectetur et delectus",
      "author_id": 1,
      "author":{"id":1,"name":"Author-A"}
    }
  ]
}

Is it possible to group the Authors data outside the Posts data for sideloading? (as shown below)

{
   posts:[{...}, {...}, {...}],
   authors:[
     {id:1, name:'Author-A'},
     {id:2, name:'Author-B'}
   ]
}

Solution

  • As a workaround, we created a custom adapter extending the Json adapter and modifying the hash to our desired format in the serializable_hash(...) method

    class CustomAdapter < ActiveModelSerializers::Adapter::Json
      def serializable_hash(options = nil)
        result_hash = super(options)
        ... code to modify hash format ...
        result_hash
      end
    end