jsonapi和active_mode_serializers如何在响应中获取关系属性?

时间:2015-07-22 06:58:56

标签: ruby-on-rails active-model-serializers json-api

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",

      }
    ]
  }
}

} }

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

2 个答案:

答案 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'

更多详情:

  1. http://jsonapi.org/format/#document-compound-documents
  2. https://github.com/rails-api/active_model_serializers/blob/a032201a91cbca407211bca0392ba881eef1f7ba/docs/general/adapters.md#included