Search code examples
ruby-on-railsjson-api

How to deserialize parameters with relationships using ActiveModelSerializers?


I used to code below to deserialize the JSON API data send from client,

def action_record_params
  ActiveModelSerializers::Deserialization.jsonapi_parse!(params)
end

When I pass the following data from the client, the deserializer cannot see relationships attributes.

Client send parameter

params = {"data": {"type": "action_record", "attributes": {"value": ""}}, "relationships": {"card": {"data": {"type": "card", "id": "#{card.id}"}}}}

Server deserialized data

{:value=>""}

How to deserialize parameters with relationships using ActiveModelSerializers?


Solution

  • Base on AMS documentation Deserialization section, which can be found below

    https://github.com/rails-api/active_model_serializers/blob/master/docs/general/deserialization.md

    The relationships can be extracted by via the option only: [:relatedModelName]. only is act as a whitelist in this case.

    Sample Data

    document = {
      'data' => {
        'id' => 1,
        'type' => 'post',
        'attributes' => {
          'title' => 'Title 1',
          'date' => '2015-12-20'
        },
        'relationships' => {
          'author' => {
            'data' => {
              'type' => 'user',
              'id' => '2'
            }
          },
          'second_author' => {
            'data' => nil
          },
          'comments' => {
            'data' => [{
              'type' => 'comment',
              'id' => '3'
            },{
              'type' => 'comment',
              'id' => '4'
            }]
          }
        }
      }
    }
    

    AMS deserialization with options

    ActiveModelSerializers::Deserialization
      .jsonapi_parse(document, only: [:title, :date, :author],
                               keys: { date: :published_at },
                               polymorphic: [:author])
    

    Output hash

    # {
    #   title: 'Title 1',
    #   published_at: '2015-12-20',
    #   author_id: '2',
    #   author_type: 'user'
    # }