ruby-on-rails - 属于帖子的自连接模型评论
问题描述
我有两个模型。我希望他们表现得像带有树状结构评论的帖子。
邮政:
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
(伪代码)的关联
解决方案
您必须提及父评论所属的帖子。
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
推荐阅读
- api - Google Apps 脚本中 UrlFetchApp.fetch 的地址不可用
- python - 更改列 openpyxl 的日期格式
- java - 如何在java中获取jTable的行或列的文本
- workflow - 在 Maximo 中将工作流路由到人员组
- html - 无法从边栏中输入的数据更新谷歌电子表格
- c# - 使用 C# 在 ASP.NET MVC 中查找站点的访问者数量
- javascript - Google Apps 脚本 - 两个函数/脚本在单独运行但不组合时有效
- r - R代码在逐行运行时执行,但不是一次全部执行
- javascript - 如何选择在 Angular 中动态加载的 html 元素?
- python - Python autopep8 和 VS Code 集成