您需要正确定义序列化器,并小心不要递归地渲染所有内容。我设置了这两个模型:
class Post < ApplicationRecord
has_many :comments, as: :commentable
end
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
end
这些序列化器:
class CommentSerializer < ActiveModel::Serializer
attributes :id, :body
belongs_to :commentable, serializer: CommentableSerializer
end
class CommentableSerializer < ActiveModel::Serializer
attributes :id, :body
has_many :comments, serializer: ShallowCommentSerializer
end
class ShallowCommentSerializer < ActiveModel::Serializer
attributes :id, :body
end
您需要另一个序列化程序来处理帖子的所有评论,以便评论不会尝试呈现帖子,而帖子会尝试呈现评论等......
保持你的
ActiveModel::Serializer.config.default_includes = '**'
配置选项已打开。
Calling http://localhost:3000/comments/1
yields:
{
"id": 1,
"body": "comment",
"commentable": {
"id": 1,
"body": "post",
"comments": [
{
"id": 1,
"body": "comment"
},
{
"id": 2,
"body": "Reply comment"
}
]
}
}
我相信,这就是您想要实现的目标。