我正在使用 Netflix 的jsonapi-rails gem 来序列化我的 API。我需要构建一个response.json
包含帖子相关评论的对象。
Post
模型:
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
多态Comment
模型
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
注释序列化器
class CommentSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :id, :created_at
belongs_to :post
end
帖子#index
class PostsController < ApplicationController
def index
@posts = Post.all
hash = PostSerializer.new(@posts).serialized_json
render json: hash
end
end
到目前为止,我只给了我评论类型和 ID,但我也需要评论body
。
请帮忙!
先谢谢了~!