2

技术背景: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",

      }
    ]
  }
}

} }

有没有办法呈现关系属性?

4

2 回答 2

5

JSON:API Spec 解释了关系数据应该是怎样的。您所要求的实际上是嵌套的,或者根据规范更好地“包含”。

我建议您阅读一下http://jsonapi.org/format/#document-compound-documents以了解有关包含/嵌套关系的规范的更多详细信息

此外,关于您的问题,您需要告诉您的序列化程序呈现包含的元素,如下所示:render @posts, include: ['authors', 'comments'] 有关更多信息,请参见此处:https ://github.com/rails-api/active_model_serializers

于 2015-07-28T15:18:49.143 回答
0

根据手册:

render json: @posts, include: ['author', 'comments', 'comments.author']
  # or
render json: @posts, include: 'author,comments,comments.author'

更多细节:

  1. http://jsonapi.org/format/#document-compound-documents
  2. https://github.com/rails-api/active_model_serializers/blob/a032201a91cbca407211bca0392ba881eef1f7ba/docs/general/adapters.md#included
于 2016-11-27T20:31:50.297 回答