Active Model Serializer 在使用 JSON API 时删除关系成员

Active Model Serializer remove relationship member when using JSON API

我正在使用带有 JSON API 适配器的最新 AMS v0.10.0.rc3

到目前为止一切正常,并且正在添加一些我想更改的有用约定。

例如,假设我有一个 Post 序列化程序和一个 Comment 序列化程序,如下所示:

class Post < ActiveModel::Serializer
  attributes :id, :title
  has_many :comments
end

class Comment < ActiveModel::Serializer
  attributes :id, :comment
  belongs_to :post
end

然后如果我请求 /posts/1 例如我得到以下

{
  "data": {
    "id": "1",
    "type": "posts",
    "attributes": {
      "title": "My awesome title",
    },
    "relationships": {
      "comments": {
        "data": [
          {
            "id": "1",
            "type": "comments"
          },
          {
            "id": "2",
            "type": "comments"
          }
        ]
      }
    }
  }
}

注意 relationships 成员是如何出现的,并且根据 spec 被标记为 MAY 的可选成员。 这是一个很好的约定,我有时需要重写。

所以我的问题是:

(如果我遗漏了一些细节,请发表评论,我会更新问题。)

目前,您最好的选择是定义两个序列化器,一个有关联,一个没有关联,并在您的渲染调用中指定要使用的序列化程序 (render json: posts, each_serializer: PostWithoutAssociationsSerializer)。

关于向关联和属性添加 include_if 选项的讨论正在进行中,如果它被合并,您可能会利用它。