使用活动模型序列化器为每个序列化项目添加全局根键和特定根键

Adding global root key and specific root key for each serialized item with active model serializer

我正在使用 active-model-serializer。我有一个对象集合,我需要 return 作为一个特殊形式的 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"
      }
    }
  ]
}

如何使用活动模型序列化器实现这一点?

对于全局根密钥,我需要将 adapter: :json 添加到渲染调用中

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

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

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