【发布时间】: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