Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

closure_tree

> 后端框架
Open source

Easily and efficiently make your ActiveRecord models support hierarchies

1.9K stars0 likes2 views
WebsiteGitHub

About

Easily and efficiently make your ActiveRecord models support hierarchies

Closure Tree

Closure_tree lets your ActiveRecord models act as nodes in a tree data structure

Common applications include modeling hierarchical data, like tags, threaded comments, page graphs in CMSes, and tracking user referrals. Dramatically more performant than ancestry and acts_as_tree, and even more awesome than awesome_nested_set, closure_tree has some great features:

  • Best-in-class select performance:
    • Fetch your whole ancestor lineage in 1 SELECT.
    • Grab all your descendants in 1 SELECT.
    • Get all your siblings in 1 SELECT.
    • Fetch all descendants as a nested hash in 1 SELECT.
    • Find a node by ancestry path in 1 SELECT.
  • Best-in-class mutation performance:
    • 2 SQL INSERTs on node creation
    • 3 SQL INSERT/UPDATEs on node reparenting
  • Support for concurrency (using with_advisory_lock)
  • Tested against ActiveRecord 7.2+ with Ruby 3.3+
  • Support for reparenting children (and all their descendants)
  • Support for single-table inheritance (STI) within the hierarchy
  • find_or_create_by_path for building out heterogeneous hierarchies quickly and conveniently
  • Support for deterministic ordering
  • Support for preordered traversal of descendants
  • Support for rendering trees in DOT format, using Graphviz
  • Excellent test coverage in a comprehensive variety of environments

See Bill Karwin's excellent Models for hierarchical data presentation for a description of different tree storage algorithms.

Table of Contents

  • Installation
  • Warning
  • Usage
  • Accessing Data
  • Polymorphic hierarchies with STI
  • Deterministic ordering
  • Concurrency
  • Multi-Database Support
  • FAQ
  • Testing
  • Change log

Installation

Note that closure_tree only supports ActiveRecord 7.2 and later, and has test coverage for MySQL, PostgreSQL, and SQLite.

  1. Add gem 'closure_tree' to your Gemfile

  2. Run bundle install

  3. Add has_closure_tree (or acts_as_tree, which is an alias of the same method) to your hierarchical model:

    ruby
    class Tag < ApplicationRecord
      has_closure_tree
    end
    
    class AnotherTag < ApplicationRecord
      acts_as_tree
    end

    Make sure you check out the large number of options that has_closure_tree accepts.

    Note: The acts_as_tree alias is only created if your model doesn't already have a method with that name. This prevents conflicts with other gems like the original acts_as_tree gem.

    IMPORTANT: Make sure you add has_closure_tree after attr_accessible and self.table_name = lines in your model.

    If you're already using other hierarchical gems, like ancestry or acts_as_tree, please refer to the warning section!

  4. Add a migration to add a parent_id column to the hierarchical model. You may want to also add a column for deterministic ordering of children, but that's optional.

    ruby
    class AddParentIdToTag < ActiveRecord::Migration[7.2]
      def change
        add_column :tags, :parent_id, :integer
      end
    end

    The column must be nullable. Root nodes have a NULL parent_id.

  5. Run rails g closure_tree:migration tag (and replace tag with your model name) to create the closure tree table for your model.

    By default the table name will be the model's table name, followed by "_hierarchies". Note that by calling has_closure_tree, a "virtual model" (in this case, TagHierarchy) will be created dynamically. You don't need to create it.

  6. Run rake db:migrate

  7. If you're migrating from another system where your model already has a parent_id column, run Tag.rebuild! and your tag_hierarchies table will be truncated and rebuilt.

    If you're starting from scratch you don't need to call rebuild!.

Warning

As stated above, using multiple hierarchy gems (like ancestry or nested set) on the same model will most likely result in pain, suffering, hair loss, tooth decay, heel-related ailments, and gingivitis. Assume things will break.

Usage

Creation

Create a root node:

ruby
grandparent = Tag.create(name: 'Grandparent')

Child nodes are created by appending to the children collection:

ruby
parent = grandparent.children.create(name: 'Parent')

Or by appending to the children collection:

ruby
child2 = Tag.new(name: 'Second Child')
parent.children << child2

Or by calling the "add_child" method:

ruby
child3 = Tag.new(name: 'Third Child')
parent.add_child child3

Or by setting the parent on the child :

ruby
Tag.create(name: 'Fourth Child', parent: parent)

Then:

ruby
grandparent.self_and_descendants.collect(&:name)
#=> ["Grandparent", "Parent", "First Child", "Second Child", "Third Child", "Fourth Child"]

child1.ancestry_path
#=> ["Grandparent", "Parent", "First Child"]

find_or_create_by_path

You can find as well as find_or_create by "ancestry paths".

If you provide an array of strings to these methods, they reference the name column in your model, which can be overridden with the :name_column option provided to has_closure_tree.

ruby
child = Tag.find_or_create_by_path(%w[grandparent parent child])

As of v5.0.0, find_or_create_by_path can also take an array of attribute hashes:

ruby
child = Tag.find_or_create_by_path([
  {name: 'Grandparent', title: 'Sr.'},
  {name: 'Parent', title: 'Mrs.'},
  {name: 'Child', title: 'Jr.'}
])

If you're using STI, The attribute hashes can contain the sti_name and things work as expected:

ruby
child = Label.find_or_create_by_path([
  {type: 'DateLabel', name: '2014'},
  {type: 'DateLabel', name: 'August'},
  {type: 'DateLabel', name: '5'},
  {type: 'EventLabel', name: 'Visit the Getty Center'}
])

Moving nodes around the tree

Nodes can be moved around to other parents, and closure_tree moves the node's descendancy to the new parent for you:

ruby
d = Tag.find_or_create_by_path %w[a b c d]
h = Tag.find_or_create_by_path %w[e f g h]
e = h.root
d.add_child(e) # "d.children << e" would work too, of course
h.ancestry_path #=> ["a", "b", "c", "d", "e", "f", "g", "h"]

When it is more convenient to simply change the parent_id of a node directly (for example, when dealing with a form <select>), closure_tree will handle the necessary changes automatically when the record is saved:

ruby
j = Tag.find 102
j.self_and_ancestor_ids #=> [102, 87, 77]
j.update parent_id: 96
j.self_and_ancestor_ids #=> [102, 96, 95, 78]

Nested hashes

hash_tree provides a method for rendering a subtree as an ordered nested hash:

ruby
b = Tag.find_or_create_by_path %w(a b)
a = b.parent
b2 = Tag.find_or_create_by_path %w(a b2)
d1 = b.find_or_create_by_path %w(c1 d1)
c1 = d1.parent
d2 = b.find_or_create_by_path %w(c2 d2)
c2 = d2.parent

Tag.hash_tree #=> {a => {b => {c1 => {d1 => {}}, c2 => {d2 => {}}}, b2 => {}}}

Tag.hash_tree(:limit_depth => 2) #=> {a => {b => {}, b2 => {}}}

b.hash_tree #=> {b => {c1 => {d1 => {}}, c2 => {d2 => {}}}}

b.hash_tree(:limit_depth => 2) #=> {b => {c1 => {}, c2 => {}}}

If your tree is large (or might become so), use :limit_depth.

Without this option, hash_tree will load the entire contents of that table into RAM. Your server may not be happy trying to do this.

HT: ancestry and elhoyos

Eager loading

Since most of closure_tree's methods (e.g. children) return regular ActiveRecord scopes, you can use the includes method for eager loading, e.g.

ruby
comment.children.includes(:author)

However, note that the above approach only eager loads the requested associations for the immediate children of comment. If you want to walk through the entire tree, you may still end up making many queries and loading duplicate copies of objects.

In some cases, a viable alternative is the following:

ruby
comment.self_and_descendants.includes(:author)

This would load authors for comment and all its descendants in a constant number of queries. However, the return value is an array of Comments, and the tree structure is thus lost, which makes it difficult to walk the tree using elegant recursive algorithms.

A third option is to use has_closure_tree_root on the model that is composed by the closure_tree model (e.g. a Post may be composed by a tree of Comments). So in post.rb, you would do:

ruby
# app/models/post.rb
has_closure_tree_root :root_comment

This gives you a plain has_one association (root_comment) to the root Comment (i.e. that with null parent_id).

It also gives you a method called root_comment_including_tree, which you can invoke as follows:

ruby
a_post.root_comment_including_tree(:author)

The result of this call will be the root Comment with all descendants and associations loaded in a constant number of queries. Inverse associations are also setup on all nodes, so as you walk the tree, calling children or parent on any node will not trigger any further queries and no duplicate copies of objects are loaded into memory.

The class and foreign key of root_comment are assumed to be Comment and post_id, respectively. These can be overridden in the usual way.

The same caveat stated above with hash_tree also applies here: this method will load the entire tree into memory. If the tree is very large, this may be a bad idea, in which case using the eager loading methods above may be preferred.

Graph visualization

to_dot_digraph is suitable for passing into Graphviz.

For example, for the above tree, write out the DOT file with ruby:

ruby
File.open("example.dot", "w") { |f| f.write(Tag.root.to_dot_digraph) }

Then, in a shell, dot -Tpng example.dot > example.png, which produces:

If you want to customize the label value, override the #to_digraph_label instance method in your model.

Just for kicks, this is the test tree I used for proving that preordered tree traversal was correct:

Available options

When you include has_closure_tree in your model, you can provide a hash to override the following defaults:

  • :parent_column_name to override the column name of the parent foreign key in the model's table. This defaults to "parent_id".
  • :hierarchy_class_name to override the hierarchy class name. This defaults to the singular name of the model + "Hierarchy", like TagHierarchy.
  • :hierarchy_table_name to override the hierarchy table name. This defaults to the singular name of the model + "_hierarchies", like tag_hierarchies.
  • :dependent determines what happens when a node is destroyed. Defaults to nullify.
    • :nullify will simply set the parent column to null. Each child node will be considered a "root" node. This is the default.
    • :adopt will move children to their grandparent (parent's parent). If there is no grandparent, children become root nodes. This is useful for maintaining tree s

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactiverecordancestrychildclosure-tree

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架