【问题标题】:Rails active_model_serializers on polymorphic nested associationRails active_model_serializers 上的多态嵌套关联
【发布时间】:2019-03-22 18:56:58
【问题描述】:

设置 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

经过一番研究

在 active_model_serializers github 文档页面上

我试过这个解决方案,也没有成功

has_many :commentable

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

请有人可以就这个问题提供小费吗?

对于一些我应该使用的东西

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

这个配置我也试过了

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

这条评论有很多可评论的回复,但只呈现一个。我想呈现此评论的其余 cmets。

标签: ruby-on-rails ruby serialization


【解决方案1】:

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

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

您需要为帖子的所有 cmets 使用另一个序列化程序,以便 cmets 不会尝试渲染帖子,而后者会尝试渲染 cmets 等...

保留你的

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"
      }
    ]
  }
}

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

【讨论】:

  • 我知道在这种情况下必须创建其他序列化程序
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多