response.json
对象,其中包含帖子的相关注释。Post
型号:class Post < ApplicationRecord
has_many :comments, as: :commentable
end
Comment
模型class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
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
class PostsController < ApplicationController
def index
@posts = Post.all
hash = PostSerializer.new(@posts).serialized_json
render json: hash
end
end
到目前为止,我只提供了评论类型和ID,但我需要评论body
。
请帮忙!
提前致谢〜!
答案 0 :(得分:3)
虽然not very intuitive这种行为是设计的。根据JSON API 关系数据和实际相关资源数据属于结构的不同对象
您可以在这里阅读更多内容:
要包含序列化程序必须包含的注释正文:
class PostSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :created_at
has_many :comments
end
class CommentSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :created_at
end
和您的控制器代码:
class HomeController < ApplicationController
def index
@posts = Post.all
options = {include: [:comments]}
hash = PostSerializer.new(@posts, options).serialized_json
render json: hash
end
end
单个帖子的响应看起来像这样:
{
"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"
}
]
}