jsonapi 和 active_mode_serializers 如何在响应中获取关系属性?
jsonapi and active_mode_serializers how to get relationship attributes in the response?
技术背景:rails 4.2.2,active_model_serializers 0.10.0.rc2
当我将产品添加到购物车时,给定一个购物车和一个产品列表,我希望得到的响应是:
{
"data": {
"id": "575",
"type": "carts",
"attributes": {
"name": "cart 1"
},
"relationships": {
"cart_products": {
"data": [
{
"type": "cart_products",
"id": "32",
"attributes": {
"product_id": 456
}
}
]
}
}
}
}
不幸的是,
当前响应是
{
"data": {
"id": "575",
"type": "carts",
"attributes": {
"name": "cart 1"
},
"relationships": {
"cart_products": {
"data": [
{
"type": "cart_products",
"id": "32",
}
]
}
}
}
}
有没有办法呈现关系属性?
JSON:API 规范解释了关系数据应该如何。您所要求的实际上是嵌套的,或者根据规范更好 "Included"。
我建议您稍微阅读一下 http://jsonapi.org/format/#document-compound-documents 以获得有关 included/nested 关系
规范的更多详细信息
此外,关于您的问题,您需要告诉您的序列化程序渲染包含的元素,如下所示:render @posts, include: ['authors', 'comments']
有关详细信息,请参阅此处:https://github.com/rails-api/active_model_serializers
根据手册:
render json: @posts, include: ['author', 'comments', 'comments.author']
# or
render json: @posts, include: 'author,comments,comments.author'
更多详情:
技术背景:rails 4.2.2,active_model_serializers 0.10.0.rc2 当我将产品添加到购物车时,给定一个购物车和一个产品列表,我希望得到的响应是:
{
"data": {
"id": "575",
"type": "carts",
"attributes": {
"name": "cart 1"
},
"relationships": {
"cart_products": {
"data": [
{
"type": "cart_products",
"id": "32",
"attributes": {
"product_id": 456
}
}
]
}
}
}
}
不幸的是, 当前响应是
{
"data": {
"id": "575",
"type": "carts",
"attributes": {
"name": "cart 1"
},
"relationships": {
"cart_products": {
"data": [
{
"type": "cart_products",
"id": "32",
}
]
}
}
} }
有没有办法呈现关系属性?
JSON:API 规范解释了关系数据应该如何。您所要求的实际上是嵌套的,或者根据规范更好 "Included"。
我建议您稍微阅读一下 http://jsonapi.org/format/#document-compound-documents 以获得有关 included/nested 关系
规范的更多详细信息此外,关于您的问题,您需要告诉您的序列化程序渲染包含的元素,如下所示:render @posts, include: ['authors', 'comments']
有关详细信息,请参阅此处:https://github.com/rails-api/active_model_serializers
根据手册:
render json: @posts, include: ['author', 'comments', 'comments.author']
# or
render json: @posts, include: 'author,comments,comments.author'
更多详情: