1

我正在使用 Netflix 的jsonapi-rails gem 来序列化我的 API。我需要构建一个response.json包含帖子相关评论的对象。

Post模型:

class Post < ApplicationRecord
  has_many :comments, as: :commentable
end

多态Comment模型

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

PostSerializer

class PostSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body
  has_many :comments, serializer: CommentSerializer, polymorphic: true
end

注释序列化器

class CommentSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body, :id, :created_at
  belongs_to :post
end

帖子#index

  class PostsController < ApplicationController
    def index
      @posts = Post.all
      hash = PostSerializer.new(@posts).serialized_json

      render json: hash
    end
  end

到目前为止,我只给了我评论类型和 ID,但我也需要评论body

在此处输入图像描述

请帮忙!

先谢谢了~!

4

1 回答 1

4

虽然不是很直观,但这种行为是设计使然的。根据 JSON API关系数据和实际相关资源数据属于不同对象的结构

你可以在这里阅读更多:

要包含 Comments 的正文,您的序列化程序必须是:

class PostSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body, :created_at
  has_many :comments
end

class CommentSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body, :created_at
end

和你的控制器代码:

class HomeController < ApplicationController
  def index
    @posts = Post.all
    options = {include: [:comments]}
    hash = PostSerializer.new(@posts, options).serialized_json

    render json: hash
  end
end

单个 Post 的响应如下所示:

{
  "data": [
    {
      "attributes": {
        "body": "A test post!"
      },
      "id": "1",
      "relationships": {
        "comments": {
          "data": [
            {
              "id": "1",
              "type": "comment"
            },
            {
              "id": "2",
              "type": "comment"
            }
          ]
        }
      },
      "type": "post"
    }
  ],
  "included": [
    {
      "attributes": {
        "body": "This is a comment 1 body!",
        "created_at": "2018-05-06 22:41:53 UTC"
      },
      "id": "1",
      "type": "comment"
    },
    {
      "attributes": {
        "body": "This is a comment 2 body!",
        "created_at": "2018-05-06 22:41:59 UTC"
      },
      "id": "2",
      "type": "comment"
    }
  ]
}
于 2018-05-06T22:46:04.910 回答