我正在使用Netflix的jsonapi-rails gem来序列化我的API。我需要构建一个response.json对象,它包含与post相关的注释。
Post模型:
class Post < ApplicationRecord
has_many :comments, as: :commentable
end多态Comment模型
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
endPostSerializer
class PostSerializer
include FastJsonapi::ObjectSerializer
attributes :body
has_many :comments, serializer: CommentSerializer, polymorphic: true
endCommentSerializer
class CommentSerializer
include FastJsonapi::ObjectSerializer
attributes :body, :id, :created_at
belongs_to :post
endPosts#index
class PostsController < ApplicationController
def index
@posts = Post.all
hash = PostSerializer.new(@posts).serialized_json
render json: hash
end
end到目前为止,我得到的只是注释类型和id,但是我也需要注释的body。

请帮帮我!
提前谢谢~!
发布于 2018-05-06 22:46:04
尽管不太直观,这种行为是由设计存在的。根据JSON,关系数据和实际相关的资源数据属于不同的结构对象。
你可以在这里读到更多:
要包含注释的主体,序列化程序必须是:
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"
}
]
}https://stackoverflow.com/questions/50198060
复制相似问题