Using Active Model Serializer, is there an easy and integrated way to return a JSON "object" (that would then be converted in a javascript object by the client framework) instead of a JSON "array" when serializing a collection? (I am quoting object and array, since the returned JSON is by essence a string).
Let's say I have the following ArticleSerializer:
class ArticleSerializer < ActiveModel::Serializer
attributes :id, :body, :posted_at, :status, :teaser, :title
end
I call it from ArticlesController:
class ArticlesController < ApplicationController
def index
@feed = Feed.new(articles: Article.all)
render json: @feed.articles, each_serializer: ArticleSerializer
end
end
Is there a way to pass an option to the serializer to make it return something like:
{"articles":
{
"1":{
...
},
"2":{
...
}
}
}
instead of
{"articles":
[
{
"id":"1",
...
},
{
"id":"2"
...
}
]
}
Edit: I guess that the approach proposed in this post (subclassing AMS ArraySerializer) might be helpful (Active Model Serializer and Custom JSON Structure)