Code Explainers
Code explainers tagged #tree-structure
ruby
class Category < ApplicationRecord belongs_to :parent, class_name: "Category", optional: true has_many :children, -> { order(:position) },
Modeling a self-referential category tree in Rails
self-referential-association
recursion
tree-structure
Intermediate
9 steps
ruby
def build_tree(rows, root_id: nil) children_by_parent = Hash.new { |hash, key| hash[key] = [] } rows.each do |row|
Building a tree from flat rows in Ruby
recursion
hash-grouping
tree-structure
Intermediate
5 steps