【发布时间】:2020-07-06 21:13:22
【问题描述】:
我只是在做一个简单的 Rails 项目,其中模型之间有很多关系:
- 一个作者可以有很多帖子
- 一个帖子可以有多个 cmets
- 喜欢和不喜欢属于每个帖子
现在,我已经渲染了作者数据(在 json 中),我得到的输出是这样的:
我们可以说它只呈现作者和帖子数据(既不是 cmets 也不是喜欢/不喜欢)。
我对 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 形式呈现作者的完整数据(意思是,预期的输出必须包括作者详细信息 + 帖子详细信息 + cmets + 喜欢 + 不喜欢)。
我已经搜索了很多来解决这个问题,但无法解决这个问题。
【问题讨论】:
-
看起来您没有在 Post 模型上为 Dis/Likecounts 定义的关系。如果您在模型中添加了
has_one,然后在序列化程序中同时定义了序列化程序,这可能会起作用
标签: ruby-on-rails json associations active-model-serializers