Active Model Serializers - Custom Adapter

I would like to refactor the existing rails APIs with active model serializers.

Unfortunately the existing API uses a slightly different JSON schema than any of the existing adapters and I was unable to recreate it with AMS.

The circuit I'm trying to rebuild looks like this:

{
  "status": 0,
  "message": "OK",
  "timestamp": 1438940571,
  "data": {
    "contacts": [
      {
        "contact": {
          "id": "1",
          "first_name": "Kung Foo",
          "last_name": "Panda",
          "created_at": "2015-07-23T14:09:20.850Z",
          "modified_at": "2015-08-04T15:21:36.639Z"
        }
      },
      {
        "contact": {
          "id": "2",
          "first_name": "Johnny",
          "last_name": "Bravo",
          "created_at": "2015-07-23T14:09:20.850Z",
          "modified_at": "2015-08-04T15:21:36.639Z"
        }
      }
    ]
  }
}

      

I'm wondering if there is a way to create a custom adapter for active model serializers or create this schema differently.

+3


source to share


1 answer


You can just use multiple serializers.

class MessageSerializer < ActiveModel::Serializer
  attributes :status, :message, :timestamp, :data
  # We could've just used that, were it not for nested hashes
  # has_many :contacts, key: :data

  attributes :data

  def data
    ActiveModel::ArraySerializer.new(object.contacts, root: 'contacts')
  end
end

class ContactSerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name, :created_at, :modified_at

  def root
    'contact'
  end
end

      

There seems to be no better way to do this



Then, somewhere in your controller:

render json: Message.serializer.new(@message, root: false)

      

0


source







All Articles