Example of using Postgres for Recursive Tree SQL in a Rails app
Ruby JavaScript
Failed to load latest commit information.
app Prefer SQL joins to subqueries Aug 22, 2012
config Add basic views for demonstration Aug 21, 2012
db
lib Basic Rails application Aug 17, 2012
log Basic Rails application Aug 17, 2012
public Add basic views for demonstration Aug 22, 2012
script Basic Rails application Aug 17, 2012
spec
vendor Basic Rails application Aug 17, 2012
.gitignore Basic Rails application Aug 17, 2012
.rspec Add Ruby implementation Aug 21, 2012
Gemfile Use standard Hashrocket setup Aug 21, 2012
Gemfile.lock
README.md
Rakefile Basic Rails application Aug 17, 2012
config.ru Basic Rails application Aug 17, 2012

README.md

Example application for demonstrating tree SQL

Setup

Obviously:

bundle

Edit config/database.yml as needed, then run:

rake db:setup db:test:prepare

Keep the tests passing:

rake

SQL

After seeding the database, you can run rails dbconsole and play with the following query:

WITH RECURSIVE search_tree(id, name, path) AS (
  SELECT id, name, ARRAY[id]
  FROM categories
  WHERE parent_id IS NULL
UNION ALL
  SELECT categories.id, categories.name, path || categories.id
  FROM search_tree
  JOIN categories ON categories.parent_id=search_tree.id
  WHERE NOT categories.id = ANY(path)
)
SELECT * FROM search_tree
ORDER BY path
;