tech context: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",
}
]
}
}
} }
有没有办法让关系属性呈现?
答案 0 :(得分:4)
JSON:API规范解释了关系数据应该如何。您要求的实际上是嵌套的,或者更好,但根据规范“包含”。
我建议您在那里阅读http://jsonapi.org/format/#document-compound-documents以获取有关包含/嵌套关系的规范的更多详细信息
此外,关于您的问题,您需要告诉序列化程序呈现包含的元素,如下所示:render @posts, include: ['authors', 'comments']
有关详细信息,请参阅此处:https://github.com/rails-api/active_model_serializers
答案 1 :(得分:0)
根据手册:
render json: @posts, include: ['author', 'comments', 'comments.author']
# or
render json: @posts, include: 'author,comments,comments.author'
更多详情: