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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A self-referential belongs_to/has_many pair lets one table represent an entire hierarchy.
- 2Recursion over the children association is the natural way to collect a subtree of records.
- 3A custom validation guarding against cycles is essential whenever a record can reference its own kind.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/modeling-a-self-referential-category-tree-in-rails-explained-ruby-88a0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.