· 大约2个月 ago
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
# 自关联:支持无限嵌套
belongs_to :parent, class_name: "Comment", optional: true
has_many :replies, class_name: "Comment", foreign_key: :parent_id, dependent: :destroy
# 排序:顶级评论时间倒序,子评论时间正序
scope :top_level, -> { where(parent_id: nil) }
scope :ordered, -> { order(created_at: :asc) }
# 构建嵌套树(视图用)
def self.build_tree(comments)
comments = comments.includes(:user).to_a
tree = []
map = {}
comments.each do |comment|
map[comment.id] = comment
comment.replies = []
end
comments.each do |comment|
if comment.parent_id
map[comment.parent_id]&.replies << comment
else
tree << comment
end
end
tree
end
end
与您的关注者分享。
回复