多态嵌套关联上的 Rails active_model_serializers [英] Rails active_model_serializers on polymorphic nested association
问题描述
在设置 gem 之后,我试图获得一个深层嵌套的多态关联数据.
after setup the gem i've tried to get a deep nested polymorphic associated data.
但 gem 只渲染 1 级关联数据.
but the gem just render the 1 level associated data.
序列化器
class CommentsSerializer < ActiveModel::Serializer
attributes :id, :title, :body, :user_id, :parent_id, :commentable_id, :commentable_type
belongs_to :user
belongs_to :commentable, :polymorphic => true
end
经过一番研究
在 active_model_serializers github 文档页面上
on the active_model_serializers github doc page
我已经尝试过这个解决方案,但也没有奏效
i've tried this solution, and did not worked either
has_many :commentable
def commentable
commentable = []
object.commentable.each do |comment|
commentable << { body: comment.body }
end
end
请问有人可以就这个问题提供一些提示吗?
please someone can spare a tip on this issue?
对于一些我应该使用的
ActiveModel::Serializer.config.default_includes = '**'
我也试过这个配置
下面的截图说明了这种情况
The screeshot below illustrate this case
这个评论有很多评论的回复,但只渲染一个.我想呈现此评论的其余评论.
this comment has many reply's by commentable, but just render one. i would like to render the rest of comments of this comment.
推荐答案
您需要正确定义序列化程序并注意不要递归渲染所有内容.我已经设置了这两个模型:
You need to properly define your serializers and be careful not to render everything recursively. I have setup these 2 models:
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
您需要另一个序列化程序来处理帖子的所有评论,以便评论不会尝试呈现帖子,而这会尝试呈现评论等...
You need another serializer for all comments of a post, so that the comments don't try to render the post, which would try to render the comments, etc...
保持你的
ActiveModel::Serializer.config.default_includes = '**'
配置选项已打开.
调用 http://localhost:3000/comments/1
产生:
{
"id": 1,
"body": "comment",
"commentable": {
"id": 1,
"body": "post",
"comments": [
{
"id": 1,
"body": "comment"
},
{
"id": 2,
"body": "Reply comment"
}
]
}
}
我相信,这就是您想要实现的目标.
which, I believe, is what you were trying to achieve.
这篇关于多态嵌套关联上的 Rails active_model_serializers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!