0

I'm using Netflix's jsonapi-rails gem to serialize my API. I need to build a response.json object that includes the associated comments for a post.

Post model:

class Post < ApplicationRecord
  has_many :comments, as: :commentable
end

Polymorphic Comment model

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

PostSerializer

class PostSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body
  has_many :comments, serializer: CommentSerializer, polymorphic: true
end

CommentSerializer

class CommentSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body, :id, :created_at
  belongs_to :post
end

Posts#index

  class PostsController < ApplicationController
    def index
      @posts = Post.all
      hash = PostSerializer.new(@posts).serialized_json

      render json: hash
    end
  end

What I've got so far only gives me the comment type and id, but I NEED the comment's body as well.

enter image description here

Please help!

Thanks in advance~!

PrimeTimeTran
  • 1,807
  • 2
  • 17
  • 29

1 Answers1

4

Although not very intuitive this behaviour is there by design. According to the JSON API relationship data and actual related resource data belong in different objects of the structure

You can read more here:

To include the body of the Comments your serializers would have to be:

class PostSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body, :created_at
  has_many :comments
end

class CommentSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body, :created_at
end

and your controller code:

class HomeController < ApplicationController
  def index
    @posts = Post.all
    options = {include: [:comments]}
    hash = PostSerializer.new(@posts, options).serialized_json

    render json: hash
  end
end

The response for a single Post would look something like this:

{
  "data": [
    {
      "attributes": {
        "body": "A test post!"
      },
      "id": "1",
      "relationships": {
        "comments": {
          "data": [
            {
              "id": "1",
              "type": "comment"
            },
            {
              "id": "2",
              "type": "comment"
            }
          ]
        }
      },
      "type": "post"
    }
  ],
  "included": [
    {
      "attributes": {
        "body": "This is a comment 1 body!",
        "created_at": "2018-05-06 22:41:53 UTC"
      },
      "id": "1",
      "type": "comment"
    },
    {
      "attributes": {
        "body": "This is a comment 2 body!",
        "created_at": "2018-05-06 22:41:59 UTC"
      },
      "id": "2",
      "type": "comment"
    }
  ]
}