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.
Please help!
Thanks in advance~!