【问题标题】:Serialize relationships with custom fields in ActiveModelSerializer序列化与 ActiveModelSerializer 中的自定义字段的关系
【发布时间】:2018-10-06 16:21:38
【问题描述】:

我在使用 ActiveModelSerializers 正确序列化我的模型时遇到了一些麻烦。设置如下:

# controllers/posts_controller.rb
class PostsController < ApplicationController

  def index
   render json: @posts, each_serializer: PostSerializer, include: %w(comments), fields: post_fields
  end

  private

  def post_fields
    { posts: [:name, :content, :author] }
  end
end

# serializers/post_serializer.rb
class PostSerializer < ActiveModelSerializer
  attributes :name, :content, :author
  has_many :comments, serializer: CommentSerializer
end

当我向posts#index 端点发出请求时,我期待一个格式为 JSON-API 规范的 JSON 响应,如下所示:

{
  "data": {
    "type": "post",
    "id": 1,
    "attributes": {
      "name": "My first post",
      "author": "Mr. Glass",
      "content": "This is my first post ..."
    },
    "relationships": {
      "comments": {
        "data": {
          "id": 1,
          "type": "comments"
        }
      }
    }
  },
  "included": {
    "type": "comments",
    "id": 1,
    "attributes": {
      "content": "First!"
    }
  }
}

然而,实际的反应是这样的:

{
  "data": {
    "type": "post",
    "id": 1,
    "attributes": {
      "name": "My first post",
      "author": "Mr. Glass",
      "content": "This is my first post ..."
    }
  },
  "included": {
    "type": "comments",
    "id": 1,
    "attributes": {
      "content": "First!"
    }
  }
}

整个关系块都不见了。有没有办法让实际响应中的关系块再次出现?

【问题讨论】:

  • 您以前有过恋爱关系吗?我在上面的代码中的任何地方都看不到它……它代表什么?您可以将其添加到include 部分吗?
  • 是的,我做到了。 relationships 块应该代表与您在here 中概述的请求的主要资源相关的项目。而且我不这么认为 - 根据 ActiveModelSerializer 文档给出的示例,我不需要指定特定的 relationships 方法。
  • 嗯,我从来没有看过 jsonapi 文档......我也不记得看到过“关系”块从轨道中出来......也许它不是自动做的? (或者我可能是错的......也不是闻所未闻:))
  • 你是对的! relationships 不是由 Rails 定义的,而是由 active_model_serializer gem 定义的,特别是仅在使用 json_api 适配器选项时(通过各种黑魔法)。
  • 酷 - 很抱歉我在这方面缺乏知识......!

标签: ruby-on-rails active-model-serializers json-api


【解决方案1】:

我想通了!

对于任何未来的读者 - 如果您希望在 ActiveModelSerializers 中出现 relationships 块以及使用 fields 选项,您需要执行以下操作:

# in your controller
render json: @posts, include: %(comments), fields: post_fields

def post_fields
  # note the inclusion of "comments" in the array of fields to be 
  # serialized. That is the change you will need to make.
  { posts: [:name, :author, :content, :comments] }
end

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 2014-02-23
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    相关资源
    最近更新 更多