繁体   English   中英

Rails active_model_serializers关于多态嵌套关联

[英]Rails active_model_serializers on polymorphic nested association

设置完宝石之后,我试图获得深层嵌套的多态关联数据。

但宝石只渲染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

经过一番研究

在active_model_serializers github doc页面上

我尝试过这个解决方案,也没用过

has_many :commentable

def commentable
  commentable = []
  object.commentable.each do |comment|
    commentable << { body: comment.body }
  end
end

请有人可以在这个问题上留意小费吗?

对于我应该使用的一些人

ActiveModel::Serializer.config.default_includes = '**'

我已经尝试过这个配置了

下面的screeshot说明了这种情况

在此输入图像描述

这个评论有很多回复是可评论的,但只是渲染一个。 我想提出本评论的其余评论。

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

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 = '**'

配置选项已打开。

调用http://localhost:3000/comments/1产生:

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

我相信,这是你想要实现的目标。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM