【问题标题】:How to deserialize parameters with relationships using ActiveModelSerializers?如何使用 ActiveModelSerializers 反序列化具有关系的参数?
【发布时间】:2017-07-11 22:00:15
【问题描述】:

我曾经在下面编写代码来反序列化客户端发送的 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 反序列化具有关系的参数?

【问题讨论】:

  • 可以使用 JSON.parse(params)
  • 我收到了 TypeError no implicit conversion of ActionController::Parameters into String

标签: ruby-on-rails json-api


【解决方案1】:

基于 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'
# }

【讨论】:

  • 如果我需要在反序列化过程中实现一些逻辑怎么办。我的意思是,如果这是一个序列化案例,我会创建一个 Serializer 类,其中覆盖 serializable_hash 方法。找不到一个很好的例子来做同样的反序列化(也许不可能?)。有什么帮助吗?
猜你喜欢
  • 2021-08-07
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 2018-06-20
  • 2018-08-31
  • 2014-05-03
相关资源
最近更新 更多