我正在使用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"
}
}
]
}
如何使用活动模型序列化程序实现这一目标?
对于全局根键,我需要添加adapter: :json
到渲染调用
render json: @tickets, root: 'placed', each_serializer: BatchItemSerializer, adapter: :json
要在每个序列化元素的根添加一个键,您可以覆盖attributes
序列化器中的方法。在这种特定情况下,您可以这样做:
def attributes(*args)
hash = super
{ params: hash }
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句