【问题标题】:Adding global root key and specific root key for each serialized item with active model serializer使用活动模型序列化程序为每个序列化项目添加全局根密钥和特定根密钥
【发布时间】:2019-05-17 10:21:46
【问题描述】:

我正在使用active-model-serializer。我有一组对象,我需要以特殊形式将它们作为 json 返回。以下是我目前所写的内容:

  @tickets = Ticket.where(status: "PLACED")
  render json: @tickets, root: 'placed', each_serializer: ItemSerializer

这是我的项目序列化程序:

class ItemSerializer < ApplicationSerializer
  attributes :pool_id, :selections

  def root
   "params"
 end
end

这是当前代码的响应:

[{\"pool_id\":759,\"selections\":\"1/2/3/4/5/6/7/8\"}]

我希望能够在数组的每个元素中添加一个根键 "params",并在数组之前添加一个全局根键 "placed",因此所需的输出是:

{ "placed": [
    {
      "params": {
        "pool_id": 123,
        "selections": "1/1/1"
      }
    }
  ]
}

如何使用主动模型序列化器实现这一目标?

【问题讨论】:

    标签: ruby-on-rails ruby active-model-serializers


    【解决方案1】:

    对于全局根键,我需要在渲染调用中添加adapter: :json

    render json: @tickets, root: 'placed', each_serializer: BatchItemSerializer, adapter: :json
    

    要在每个序列化元素的根部添加一个键,您可以覆盖序列化程序中的attributes 方法。在这种特定情况下,您可以这样做:

      def attributes(*args)
        hash = super
        { params: hash }
      end
    

    【讨论】:

      猜你喜欢
      • 2011-02-27
      • 2013-10-22
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多