Anders Anders - 1 year ago 100
Ruby Question

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

I have a rails app in which I use the gem

. In my responses I would like to nest my results inside a
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

If I instead use
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 Source

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

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

ActiveModelSerializers.config.adapter = :bikeshed
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download