Rails with_recursive: Recursive CTE in ActiveRecord
Walk category trees and org charts in one query, with depth, path and cycle protection.
Use with_recursive on any model in Rails 7.2 or newer. Pass it a name and two relations, the starting row and the step that walks one level further. Rails writes WITH RECURSIVE ... UNION ALL ..., and you point from at the CTE to read its rows. Rails 7.1 only has with, so older apps need raw SQL or a gem.
Every example below ran on ActiveRecord 8.1.1 with PostgreSQL 16.15 on 25 November 2026. The SQL shown is the SQL Rails produced.
The schema used in every example
class Category < ApplicationRecord
belongs_to :parent, class_name: "Category", optional: true
end
# categories: id, name (string), parent_id (references categories)
Seven rows: Electronics (1) has Computers (2) and Phones (5). Computers has Laptops (3). Laptops has Gaming laptops (4). Books (6) has Fiction (7).
Find every descendant of one row
SQL:
WITH RECURSIVE category_tree AS (
SELECT * FROM categories WHERE id = 1
UNION ALL
SELECT c.* FROM categories c
JOIN category_tree t ON c.parent_id = t.id
)
SELECT * FROM category_tree
ActiveRecord:
anchor = Category.where(id: 1)
step = Category.joins("JOIN category_tree ON categories.parent_id = category_tree.id")
Category.with_recursive(category_tree: [anchor, step])
.from("category_tree AS categories")
.order(:id)
.pluck(:id, :name)
# => [[1, "Electronics"], [2, "Computers"], [3, "Laptops"], [4, "Gaming laptops"], [5, "Phones"]]
Generated SQL (before order and pluck):
WITH RECURSIVE "category_tree" AS (
SELECT "categories".* FROM "categories" WHERE "categories"."id" = 1
UNION ALL
SELECT "categories".* FROM "categories"
JOIN category_tree ON categories.parent_id = category_tree.id
)
SELECT "categories".* FROM category_tree AS categories
The array holds two relations. The first is the anchor, the second is the recursive step. Rails joins them with UNION ALL.
Do not skip .from("category_tree AS categories"). Without it Rails builds SELECT "categories".* FROM "categories", which reads the whole table and ignores the CTE. In my run .count returned 7 instead of 5, with no error.
Add depth and a readable path
The two-relation form cannot add computed columns to both halves. For that, pass one raw SQL string wrapped in Arel.sql:
sql = <<~SQL.squish
SELECT id, name, parent_id, 0 AS depth, name::text AS path
FROM categories WHERE id = 1
UNION ALL
SELECT c.id, c.name, c.parent_id, t.depth + 1, t.path || ' > ' || c.name
FROM categories c JOIN category_tree t ON c.parent_id = t.id
SQL
Category.with_recursive(category_tree: Arel.sql(sql))
.from("category_tree AS categories")
.select("categories.*")
.order(Arel.sql("path"))
.each { |c| puts "#{c.depth} #{c.path}" }
# 0 Electronics
# 1 Electronics > Computers
# 2 Electronics > Computers > Laptops
# 3 Electronics > Computers > Laptops > Gaming laptops
# 1 Electronics > Phones
depth and path show up as attributes on each record. Sorting by path gives a tree order for free. order with a raw string needs Arel.sql, otherwise Rails raises ActiveRecord::UnknownAttributeReference.
Walk up instead of down
Swap the join direction to get the ancestors of Gaming laptops (id 4):
start = Category.where(id: 4)
up = Category.joins("JOIN ancestors ON categories.id = ancestors.parent_id")
Category.with_recursive(ancestors: [start, up])
.from("ancestors AS categories")
.pluck(:id, :name)
# => [[4, "Gaming laptops"], [3, "Laptops"], [2, "Computers"], [1, "Electronics"]]
The recursion stops by itself at the root, because the root has a NULL parent_id and the join finds nothing.
Use the tree as a filter
You often want the full records of a subtree, with scopes and other conditions on top. Select the ids and feed them to where:
ids = Category.with_recursive(category_tree: [anchor, step])
.from("category_tree AS categories")
.select(:id)
Category.where(id: ids).where.not(id: 1).count
# => 4
SELECT "categories".* FROM "categories"
WHERE "categories"."id" IN (
WITH RECURSIVE "category_tree" AS ( ... )
SELECT "categories"."id" FROM category_tree AS categories
)
PostgreSQL accepts a WITH clause inside a subquery, so this stays one round trip.
Stop infinite loops
If one row points back to a descendant, the recursion never ends. I made Electronics a child of Gaming laptops and ran the first query with limit(12). It returned [1, 2, 5, 3, 4, 1, 2, 5, 3, 4, 1, 2]. Without the limit, the query never finishes on its own. Three guards work:
- A depth limit in the step, as
WHERE t.depth < 10. On my cyclic data it returned 14 rows and stopped. -
UNIONinstead ofUNION ALLin a raw SQL string. It drops rows that repeat an earlier row, and it ended the loop on[1, 2, 5, 3, 4]. It only works when the whole row repeats exactly, so it fails as soon as you add adepthorpathcolumn that changes on every pass. - PostgreSQL 14 and newer: the
CYCLEclause. It marks the row where the loop closes.
The CYCLE clause goes after the CTE body, and with_recursive has no hook for it, so run it as raw SQL:
ActiveRecord::Base.connection.select_rows(<<~SQL)
WITH RECURSIVE category_tree AS (
SELECT id, name, parent_id FROM categories WHERE id = 1
UNION ALL
SELECT c.id, c.name, c.parent_id
FROM categories c JOIN category_tree t ON c.parent_id = t.id
) CYCLE id SET is_cycle USING path
SELECT id, name, is_cycle FROM category_tree
SQL
# => [[1, "Electronics", false], [2, "Computers", false], [5, "Phones", false],
# [3, "Laptops", false], [4, "Gaming laptops", false], [1, "Electronics", true]]
The last row has is_cycle = true, and the recursion stops there. The best fix is still a validation or a database check so a cycle cannot be saved.
Which form to use
| Need | Use |
|---|---|
| All descendants or ancestors | with_recursive(name: [anchor, step]).from("name AS table") |
| Depth, path or other computed columns | One Arel.sql string with UNION ALL
|
| Full records filtered by the tree | where(id: tree.select(:id)) |
| Data that may contain a cycle | Depth limit, UNION, or CYCLE (PostgreSQL 14+) |
| Rails 7.1 or older |
with only, so raw SQL or a gem |
Before you ship any of these, call .to_sql and read the statement. Then run EXPLAIN ANALYZE: the step joins the table once per level, so an index on parent_id matters on a large table. This post on reading generated SQL shows how. The UNION ALL behaviour is the same one covered in SQL UNION in Rails ActiveRecord. For plain conditions on the final query, see Rails where clause: multiple conditions and OR logic.
Have a WITH RECURSIVE query you need to translate? Paste it into the SQL to ActiveRecord converter and compare the output with .to_sql in your console.
Frequently asked questions
- Which Rails version added with_recursive?
- Rails 7.2 added with_recursive. Rails 7.1 added with, which writes a plain CTE but not WITH RECURSIVE.
- Why does my with_recursive query return the whole table?
- You did not point from at the CTE. Without from("cte_name AS table_name"), Rails selects from the real table and ignores the CTE rows.
- How do I add depth or a path column to a recursive CTE in ActiveRecord?
- Pass one raw SQL string wrapped in Arel.sql instead of the two-relation array, and add the computed columns to both the anchor and the recursive step.
- How do I stop a recursive CTE from looping forever?
- Add a depth limit in the recursive step, use UNION instead of UNION ALL when whole rows repeat, or use the PostgreSQL 14+ CYCLE clause through raw SQL.
- Can I filter a model by a recursive CTE?
- Yes. Build the CTE relation, select(:id) from it, and pass it to where(id: relation). PostgreSQL accepts the WITH clause inside the subquery.
Was this article helpful?
Your feedback helps us improve our content
How We Verify Conversions
Every conversion shown on this site follows a strict verification process to ensure correctness:
- Compare results on same dataset — We run both SQL and ActiveRecord against identical test data and verify results match
-
Check generated SQL with
to_sql— We inspect the actual SQL Rails generates to catch semantic differences (INNER vs LEFT JOIN, WHERE vs ON, etc.) - Add regression tests for tricky cases — Edge cases like NOT EXISTS, anti-joins, and predicate placement are tested with multiple scenarios
- Tested on Rails 8.1.1 — All conversions verified on current Rails version to ensure compatibility
Last updated: November 25, 2026
Try These Queries in Our Converter
See the SQL examples from this article converted to ActiveRecord—and compare the SQL Rails actually generates.
Deep Dive into ActiveRecord
Raza Hussain
Full-stack developer specializing in Ruby on Rails, React, and modern JavaScript. 15+ years upgrading and maintaining production Rails apps. Led Rails 4/5 → 7 upgrades with 40% performance gains, migrated apps from Heroku to Render cutting costs by 35%, and built systems for StatusGator, CryptoZombies, and others. Available for Rails upgrades, performance work, and cloud migrations.
More on PostgreSQL Features in Rails
ActiveRecord where vs find_by — Which to Use When
where returns a relation, find_by returns one record or nil. Here's when each is correct, what breaks if you pick wrong, and Rails 7/8 production patterns.
SQL CASE WHEN in Rails ActiveRecord
Write SQL CASE WHEN in ActiveRecord with select, sum, group, order, in_order_of and Arel. Tested on Rails 8.1.1 with the real SQL output.
SQL UNION in Rails ActiveRecord: Three Tested Ways
ActiveRecord has no union method. Use or, from with a raw UNION, or find_by_sql. Tested on Rails 8.1.1, with the SQL each one runs.
Leave a Response
Responses (0)
No responses yet
Be the first to share your thoughts