Ruby on rails 多态嵌套关联上的Rails活动\u模型\u序列化程序

Ruby on rails 多态嵌套关联上的Rails活动\u模型\u序列化程序,ruby-on-rails,ruby,serialization,Ruby On Rails,Ruby,Serialization,在设置gem之后,我尝试获取一个深度嵌套的多态关联数据 但是gem只呈现1级关联数据 序列化程序 class CommentsSerializer < ActiveModel::Serializer attributes :id, :title, :body, :user_id, :parent_id, :commentable_id, :commentable_type belongs_to :user belongs_to :commentable, :polymorph

在设置gem之后,我尝试获取一个深度嵌套的多态关联数据

但是gem只呈现1级关联数据

序列化程序

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
我已经尝试过这个配置了

下面的图表说明了这种情况


此评论有许多可评论的回复,但仅呈现一条。我想呈现此注释的其余注释。

您需要正确定义序列化程序,注意不要递归呈现所有内容。我已设置了以下两种型号:

class Post < ApplicationRecord
  has_many :comments, as: :commentable
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end
配置选项已打开

呼叫
http://localhost:3000/comments/1
收益率:

{
  "id": 1,
  "body": "comment",
  "commentable": {
    "id": 1,
    "body": "post",
    "comments": [
      {
        "id": 1,
        "body": "comment"
      },
      {
        "id": 2,
        "body": "Reply comment"
      }
    ]
  }
}

我相信,这正是您试图实现的。

您所说的是“深度嵌套数据”,AMS仅呈现“1级”数据,而代码仅显示1级关联。请指定您试图序列化的内容以及预期的输出。@MarcinKołodziej感谢您的关注,好吧,多态性自身的模型具有深层嵌套关联。好的,我要编辑我的问题,所以,你想呈现一个注释,它有一个
可注释的
,哪个有更多的注释?你想让所有其他的评论都可以评论吗?@MarcinKołodziej是的,就是这样我知道在这种情况下必须创建其他序列化程序吗
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 = '**'
{
  "id": 1,
  "body": "comment",
  "commentable": {
    "id": 1,
    "body": "post",
    "comments": [
      {
        "id": 1,
        "body": "comment"
      },
      {
        "id": 2,
        "body": "Reply comment"
      }
    ]
  }
}