活动模型序列化器不呈现收集的根密钥 - 版本 - 0.10.6
Active Model Serializer not rendering the root key for collection - Version- 0.10.6
我正在使用 'active_model_serializers', '~> 0.10.6'
呈现我的 API 响应。对于我的 index
操作,我正在这样做 -
render json: @items, root: 'data', each_serializer: ItemsSerializer
但在我的回复中,我没有收到 root key
- data
[
{
"id": 85,
"title": "B",
"source": "manager_added",
"shared": true,
"status": "suggested",
"item_type": "action_item",
"manager": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
},
"reportee": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
}
},
{
"id": 87,
"title": "D",
"source": "manager_added",
"shared": true,
"status": "suggested",
"item_type": "action_item",
"manager": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
},
"reportee": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
}
}
]
我做错了什么?
AMS 最难的部分是找到正确的文档。根据您提到的版本,这里是文档 link:
https://github.com/rails-api/active_model_serializers/tree/0-10-stable/docs
有 3 个适配器:
:default
(不会有root,基本上root
key没用,加了就算了)
:json
(这是你需要的,你可以添加自定义root
键。https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#example-output-1)
:json_api
(默认的 root
键是 data
,但你可以自定义,也许你可以使用这个,但它会改变你的响应的整个结构 json 变成类似:https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#example-output-2)
答案:
render json: @items, root: 'data', adapter: :json, each_serializer: ItemsSerializer
或
render json: @items, adapter: :json, each_serializer: ItemsSerializer
我正在使用 'active_model_serializers', '~> 0.10.6'
呈现我的 API 响应。对于我的 index
操作,我正在这样做 -
render json: @items, root: 'data', each_serializer: ItemsSerializer
但在我的回复中,我没有收到 root key
- data
[
{
"id": 85,
"title": "B",
"source": "manager_added",
"shared": true,
"status": "suggested",
"item_type": "action_item",
"manager": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
},
"reportee": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
}
},
{
"id": 87,
"title": "D",
"source": "manager_added",
"shared": true,
"status": "suggested",
"item_type": "action_item",
"manager": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
},
"reportee": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
}
}
]
我做错了什么?
AMS 最难的部分是找到正确的文档。根据您提到的版本,这里是文档 link: https://github.com/rails-api/active_model_serializers/tree/0-10-stable/docs
有 3 个适配器:
:default
(不会有root,基本上root
key没用,加了就算了):json
(这是你需要的,你可以添加自定义root
键。https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#example-output-1):json_api
(默认的root
键是data
,但你可以自定义,也许你可以使用这个,但它会改变你的响应的整个结构 json 变成类似:https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#example-output-2)
答案:
render json: @items, root: 'data', adapter: :json, each_serializer: ItemsSerializer
或
render json: @items, adapter: :json, each_serializer: ItemsSerializer