Как отобразить глубоко вложенные ассоциации в json с помощью сериализатора в рельсах? - PullRequest
1 голос
/ 26 марта 2020

Я просто работаю над проектом простой рельсы, в котором модели имеют много взаимосвязей между ними:

  1. Автор может иметь много сообщений
  2. Сообщение может иметь много комментариев
  3. лайки и антипатии принадлежат каждому посту

Теперь я предоставил данные об авторах (в json) и получаю следующий вывод:

enter image description here

Как мы можем сказать, он отображает только данные автора и публикации (ни комментариев, ни лайков / антипатий).

Я очень новичок в RubyOnRails. Итак, все, что я пробовал до сих пор, это:

Контроллер:

class AuthorsController < ApplicationController
    def show
        @auth = Author.find_by(id: params[:id])
        render json: @auth
    end
end

Модели:

class Author < ApplicationRecord
    has_many :posts
end

class Comment < ApplicationRecord
    belongs_to: post
end

class Dislike < ApplicationRecord
    belongs_to: post
end

class Like < ApplicationRecord
    belongs_to: post
end

class Post < ApplicationRecord
    has_many :comments
end

Сериализаторы:

class AuthorSerializer < ActiveModel::Serializer
  attributes :id, :name, :age
  has_many :posts
end

class CommentSerializer < ActiveModel::Serializer
  attributes :id, :content, :username
end

class DislikeSerializer < ActiveModel::Serializer
  attributes :id, :dislikecount
end

class LikeSerializer < ActiveModel::Serializer
  attributes :id, :likecount
end

class PostSerializer < ActiveModel::Serializer
  attributes :name, :content
  has_many :comments, serializer: CommentSerializer  
end

schema.rb:

ActiveRecord::Schema.define(version: 2020_03_25_091544) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "authors", force: :cascade do |t|
    t.string "name"
    t.integer "age"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "comments", force: :cascade do |t|
    t.string "content"
    t.string "username"
    t.bigint "post_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["post_id"], name: "index_comments_on_post_id"
  end

  create_table "dislikes", force: :cascade do |t|
    t.integer "dislikecount"
    t.bigint "post_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["post_id"], name: "index_dislikes_on_post_id"
  end

  create_table "likes", force: :cascade do |t|
    t.integer "likecount"
    t.bigint "post_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["post_id"], name: "index_likes_on_post_id"
  end

  create_table "posts", force: :cascade do |t|
    t.string "name"
    t.string "content"
    t.bigint "author_id"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["author_id"], name: "index_posts_on_author_id"
  end

end

Теперь я просто хочу отобразить полные данные автора (значит, ожидаемый результат должен включать сведения об авторе + подробности сообщения + комментарии + отметки + лайки) в json form.

Я много искал, чтобы решить эту проблему, но не смог решить эту проблему.

1 Ответ

0 голосов
/ 26 марта 2020

Вам необходимо внести 2 изменения в свой код -

class Post < ApplicationRecord
  has_many :comments
  has_many :likes
  has_many :dislikes
  belongs_to :author
end

class PostSerializer < ActiveModel::Serializer
  attributes :name, :content
  has_many :comments, serializer: CommentSerializer
  has_many :likes
  has_many :dislikes  
end
...