Как включить вложенный ресурс, имеющий полиморфную ассоциацию с ActiveRecordSerializer? - PullRequest
0 голосов
/ 06 мая 2018

Я использую гем jsonapi-rails от Netflix для сериализации моего 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

То, что у меня есть, дает мне только тип комментария и идентификатор, но мне НУЖНО комментария body.

enter image description here

Пожалуйста, помогите!

Заранее спасибо ~!

1 Ответ

0 голосов
/ 07 мая 2018

Хотя не очень интуитивно понятен такое поведение есть в дизайне. Согласно 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"
    }
  ]
}
...