Book

 · 大約2個月 ago

tree

# 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

Book · 大約2個月

c11

Book · 大約2個月

c22

Book · 大約2個月

c33

Aaron · 大約2個月

可以

Aaron · 大約2個月

Book · 大約2個月

c1

Book · 大約2個月

c2

Aaron · 大約2個月

厉害👍

Book · 大約2個月

部署,production 见

Download Pickful App

Better experience on mobile

iOS QR

iOS

Android QR

Android

APK QR

APK