首页 > 解决方案 > 属于帖子的自连接模型评论

问题描述

我有两个模型。我希望他们表现得像带有树状结构评论的帖子。

邮政:

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"]。但是帖子是存在的。运行时未设置帖子 IDcomment.children.new(content: 'text')如何创建类似children belongs_to :post, through: :parents(伪代码)的关联

标签: ruby-on-railsself-join

解决方案


您必须提及父评论所属的帖子。

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

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

在模型/comment.rb

before_save :set_post_id

private

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

推荐阅读