Search code examples
ruby-on-railsactive-model-serializersjson-api

jsonapi and active_mode_serializers how to get relationship attributes in the response?


tech context: rails 4.2.2, active_model_serializers 0.10.0.rc2 Given a cart and a list of product when I add a product to the cart I expect to get as response:

{
"data": {
  "id": "575",
  "type": "carts",
  "attributes": {
    "name": "cart 1"
  },
  "relationships": {
    "cart_products": {
      "data": [
        {
          "type": "cart_products",
          "id": "32",
          "attributes": {
            "product_id": 456
          }
        }
      ]
    }
  }
}
}

unfortunately , the current response is

{
"data": {
"id": "575",
"type": "carts",
"attributes": {
  "name": "cart 1"
},
"relationships": {
  "cart_products": {
    "data": [
      {
        "type": "cart_products",
        "id": "32",

      }
    ]
  }
}

} }

is there a way to have relationship attributes rendered?


Solution

  • The JSON:API Spec explains how the relationship data should be. What you are asking for is actually meant to be nested, or better yet "Included" as per the spec.

    I would suggest you read a bit over there http://jsonapi.org/format/#document-compound-documents for more details on the spec regarding included/nested relationships

    Also, regarding your question, you need to tell your serializer to render included elements, like so: render @posts, include: ['authors', 'comments'] See here for more info: https://github.com/rails-api/active_model_serializers