如何使用 ActiveModelSerializers 反序列化具有关系的参数?

How to deserialize parameters with relationships using ActiveModelSerializers?

我曾经在下面编写代码来反序列化从客户端发送的 JSON API 数据,

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

当我从客户端传递以下数据时,反序列化器看不到 relationships 属性。

客户端发送参数

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

服务器反序列化数据

{:value=>""}

如何使用 ActiveModelSerializers 反序列化具有关系的参数?

基于 AMS 文档反序列化部分,可在下方找到

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

可以通过选项 only: [:relatedModelName] 提取关系。 only 在这种情况下充当白名单。

示例数据

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 反序列化

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

输出哈希

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