【问题标题】:Associations and models for structure of comments and subcomments评论和子评论结构的关联和模型
【发布时间】:2018-08-17 12:57:11
【问题描述】:

我对如何将我的数据库建模为以下结构有疑问:

我有一个包含 cmets 的帖子,这个 cmets 可能有也可能没有很多 subcmets,这些 subcmets 可以有很多 cmets / subcmets 等等。

我的结构的一个例子:

我知道我必须有一个评论表,但我不确定我是否必须通过一个表子cmets 创建一个 has_many 关系,或者通过自动重新对齐来做到这一点。谁能给你一个想法?

我在 cmets 中添加了 self join:

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :post
  belongs_to :parent, :class_name => "Comment"
  has_many :child_comments, :class_name => "Comment", :foreign_key => "parent_id"
end

我的其他模特是:

class Post < ApplicationRecord
  belongs_to :user
  has_many :comments
  validates :title, presence: true
  validates :body, presence: true
end


class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :posts
  has_many :comments
end

当我尝试使用以下命令创建新评论时:

Comment.create(body: 'comment', user_id: 1, post_id: 1, parent_id: 1)

我明白了:

(0.6ms) BEGIN User Load (66.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]] 发布 加载 (35.8 毫秒) SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]] 评论加载 (13.4ms) SELECT "cmets".* FROM "cmets" WHERE "cmets"."id" = $1 限制 $2 [["id", 1], ["LIMIT", 1]] (0.5ms) 回滚 => #

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我会使用自引用模型,例如:

    class Comment < ActiveRecord::Base
      belongs_to :parent, :class_name => "Comment"
      has_many :child_comments, :class_name => "Comment", :foreign_key => "parent_id"
    end
    

    这将创建一个树结构模型,其中每条评论都属于一个父级。

    【讨论】:

    • 嗯...但是如果是图片中1.1这样的主评论,评论可能没有父评论。
    • 当我尝试使用以下命令创建评论时:Comment.create(body: 'comment', user_id: 1, post_id: 1, parent_id: 1) 数据库不接受并回滚
    • 我用日志和其他信息编辑了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2022-09-30
    • 2012-08-23
    相关资源
    最近更新 更多