У меня две модели. Я хочу, чтобы они вели себя как пост с древовидными комментариями.
Сообщение:
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"]
. Но пост существует. При запуске comment.children.new(content: 'text')
идентификатор записи не устанавливается. Как создать ассоциацию, например children belongs_to :post, through: :parents
(псевдокод)