ActiveModelSerializers (AMS) is often said "an alternative to Jbuilder", but AMS is a kind of decorator which knows only how to serialize the target objects. On the other hand, Jbuilder is a library for the view of MVC.
So, it's a bit tough with only AMS to compose complex JSONs like this:
{
"users": [
],
"aminals": [
],
"insects": [
]
}
because AMS objects don't know how to make an entire response; they have concerns just about their target objects.
In this case, using Jbuilder is one solution (I never say the best solution) as follows:
# app/controllers/creatures_controller.rb
class CreaturesController
def index
@users = User.all
@animals = Animal.all
@insects = Insect.all
end
end
# app/views/creatures/index.json.jbuilder
json.users ActiveModelSerializers::SerializableResource.new(@users)
json.animals ActiveModelSerializers::SerializableResource.new(@animals)
json.insects ActiveModelSerializers::SerializableResource.new(@insects)
Pass scope
and scope_name
as options to designate them as current_user
when initializing ActiveModelSerializers::SerializableResource
:
options = { scope: current_user, scope_name: :current_user }
json.resources ActiveModelSerializers::SerializableResource.new(@resources, options)