如何包含与ActiveRecordSerializer具有多态关联的嵌套资源?

时间:2018-05-06 09:09:30

标签: ruby-on-rails active-model-serializers netflix fastjsonapi

我正在使用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

CommentSerializer

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

帖子#索引

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

      render json: hash
    end
  end

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

enter image description here

请帮忙!

提前致谢〜!

1 个答案:

答案 0 :(得分:3)

虽然not very intuitive这种行为是设计的。根据JSON API 关系数据和实际相关资源数据属于结构的不同对象

您可以在这里阅读更多内容:

要包含序列化程序必须包含的注释正文:

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

单个帖子的响应看起来像这样:

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