Anders Anders - 6 months ago 19
Ruby Question

Rails ActiveModel::Serializer nest response in "data": parent

I have a rails app in which I use the gem

active_model_serializers
. In my responses I would like to nest my results inside a
"data":
parent. Currently when I don't get any data for a response I get the following JSON:

[]


What I want is something like this:

{
"data": []
}


I would also like to use the same format in cases where I have data, like this:

{
"data": [
{
"id": 135,
[...]


I've managed to get the structure I want by using
render json
, like this:

render json: { data: respond_values}


But in this case my serialiser gets ignored and all the attributes in my model gets returned. My serialiser looks like this:

class TranslationSerializer < ActiveModel::Serializer
attributes :id, :value, :created_at, :updated_at, :language_id
has_one :language
has_one :localized_string, serializer: LocalizedStringParentSerializer
end


If I instead use
respond_with
my serialiser works but I don't get the structure I want - the data parent / container is missing.

Any ideas on what I need to to to get my serialiser to work properly?

max max
Answer

First off unless you need to support a legacy API use the JSON:API adapter:

By default ActiveModelSerializers will use the Attributes Adapter (no JSON root). But we strongly advise you to use JsonApi Adapter, which follows 1.0 of the format specified in jsonapi.org/format.

While nobody fully agrees with all the design decisions in JSON:API it is widely supported by front-end frameworks such as Ember and Angular and is likely to gain further traction.

Otherwise you would need to create your own adapter since the JSON adapter does not allow you to set the root key.

# lib/active_model_serializers/adapters/bikeshed_adapter.rb
module ActiveModelSerializers
  module Adapters
    class BikeshedAdapter < Json 
      def root
        :data
      end
    end
  end
end

ActiveModelSerializers.config.adapter = :bikeshed