首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何包含与ActiveRecordSerializer具有多态关联的嵌套资源?

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

Stack Overflow用户
提问于 2018-05-06 09:09:29
回答 1查看 2.6K关注 0票数 1

我正在使用Netflix的jsonapi-rails gem来序列化我的API。我需要构建一个response.json对象,它包含与post相关的注释。

Post模型:

代码语言:javascript
复制
class Post < ApplicationRecord
  has_many :comments, as: :commentable
end

多态Comment模型

代码语言:javascript
复制
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

PostSerializer

代码语言:javascript
复制
class PostSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body
  has_many :comments, serializer: CommentSerializer, polymorphic: true
end

CommentSerializer

代码语言:javascript
复制
class CommentSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body, :id, :created_at
  belongs_to :post
end

Posts#index

代码语言:javascript
复制
  class PostsController < ApplicationController
    def index
      @posts = Post.all
      hash = PostSerializer.new(@posts).serialized_json

      render json: hash
    end
  end

到目前为止,我得到的只是注释类型和id,但是我也需要注释的body

请帮帮我!

提前谢谢~!

EN

回答 1

Stack Overflow用户

发布于 2018-05-06 22:46:04

尽管不太直观,这种行为是由设计存在的。根据JSON,关系数据和实际相关的资源数据属于不同的结构对象。

你可以在这里读到更多:

  • 取取关系
  • 列入相关资源

要包含注释的主体,序列化程序必须是:

代码语言:javascript
复制
class PostSerializer
  include FastJsonapi::ObjectSerializer
  attributes :body, :created_at
  has_many :comments
end

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

你的控制器代码:

代码语言:javascript
复制
class HomeController < ApplicationController
  def index
    @posts = Post.all
    options = {include: [:comments]}
    hash = PostSerializer.new(@posts, options).serialized_json

    render json: hash
  end
end

对于一篇文章的回应应该是这样的:

代码语言:javascript
复制
{
  "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"
    }
  ]
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50198060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档