序列化与ActiveModelSerializer中自定义字段的关系

时间:2018-04-26 04:46:53

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

使用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!"
    }
  }
}

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

1 个答案:

答案 0 :(得分: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

希望有所帮助!