ruby 54 lines · 9 steps

Modeling a self-referential category tree in Rails

A single Category model becomes a full tree by pointing at itself, with helpers to walk ancestors, gather descendants, and prevent cycles.

Explained by highlit
1class Category < ApplicationRecord
2 belongs_to :parent, class_name: "Category", optional: true
3 has_many :children,
4 -> { order(:position) },
5 class_name: "Category",
6 foreign_key: :parent_id,
7 inverse_of: :parent,
8 dependent: :destroy
9 
10 has_many :products, dependent: :nullify
11 
12 scope :roots, -> { where(parent_id: nil).order(:position) }
13 scope :active, -> { where(active: true) }
14 
15 validates :name, presence: true
16 validate :parent_cannot_be_descendant
17 
18 def self.filter_tree
19 roots.active.includes(children: { children: :children })
20 end
21 
22 def ancestors
23 node, chain = parent, []
24 while node
25 chain.unshift(node)
26 node = node.parent
27 end
28 chain
29 end
30 
31 def self_and_descendant_ids
32 ids = [id]
33 children.each { |child| ids.concat(child.self_and_descendant_ids) }
34 ids
35 end
36 
37 def descendant_products
38 Product.where(category_id: self_and_descendant_ids)
39 end
40 
41 def depth
42 ancestors.size
43 end
44 
45 private
46 
47 def parent_cannot_be_descendant
48 return if parent_id.blank? || new_record?
49 
50 if self_and_descendant_ids.include?(parent_id)
51 errors.add(:parent_id, "cannot be one of its own descendants")
52 end
53 end
54end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A self-referential belongs_to/has_many pair lets one table represent an entire hierarchy.
  2. 2Recursion over the children association is the natural way to collect a subtree of records.
  3. 3A custom validation guarding against cycles is essential whenever a record can reference its own kind.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Modeling a self-referential category tree in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code