[英]Rails active_model_serializers on polymorphic nested association
after setup the gem i've tried to get a deep nested polymorphic associated data. 设置完宝石之后,我试图获得深层嵌套的多态关联数据。
but the gem just render the 1 level associated data. 但宝石只渲染1级关联数据。
the serializer 序列化器
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
After some research 经过一番研究
on the active_model_serializers github doc page 在active_model_serializers github doc页面上
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? 请有人可以在这个问题上留意小费吗?
and for some that should i use 对于我应该使用的一些人
ActiveModel::Serializer.config.default_includes = '**'
i've tried already this config too 我已经尝试过这个配置了
The screeshot below illustrate this case 下面的screeshot说明了这种情况
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
And these serializers: 这些序列化器:
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... 你需要一个帖子的所有评论的另一个序列化程序,以便评论不会尝试呈现帖子,这将尝试呈现评论等...
Keep your 保持你的
ActiveModel::Serializer.config.default_includes = '**'
config option turned on. 配置选项已打开。
Calling http://localhost:3000/comments/1
yields: 调用
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. 我相信,这是你想要实现的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.