属于 Posts 的自连接模型 Comment

self-joined model Comment that belongs to Posts

我有两个模型。我希望他们的行为像 post 一样,带有树状结构的评论。

Post:

class Post < ApplicationRecord
  has_many :comments
end

评论:

class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :parent, class_name: 'Comment', optional: true
  has_many :children, class_name: 'Comment', foreign_key: 'parent_id'
end

当我通过

在控制台中创建评论时
post = Post.create(title: 'Title', content: 'text')
comment = post.comments.create(content: 'text')
child = comment.children.create(content: 'text')
pp child

这是我得到的:

[22] pry(main)> child = comment.children.create(content: 'text')
   (0.2ms)  begin transaction
   (0.2ms)  rollback transaction
=> #<Comment:0x00007f16ec59cc20
  id: nil,
 content: "text",
 post_id: nil,
 parent_id: 5,
 created_at: nil,
 updated_at: nil>

我尝试了一点但没有成功,自助加入指南也没有帮助。我的模型缺少什么代码?

更新

child 未保存到数据库中。错误:["Post must exist"]。但是 post 存在。 Post 当我 运行 comment.children.new(content: 'text') 时没有设置 id 如何创建像 children belongs_to :post, through: :parents 这样的关联(伪代码)

你必须提到 post 父评论属于什么。

comment.children.new(content: "text", post: comment.post)

或者您也可以在模型的回调中执行此操作。

在models/comment.rb

before_save :set_post_id

private

def set_post_id
  self.post_id = post.id || parent.post.id
end