A Ruby gem for efficiently modeling hierarchical data in ActiveRecord using closure tree tables.
Closure Tree is a Ruby gem that allows ActiveRecord models to efficiently represent hierarchical data using the closure table pattern. It solves the problem of modeling tree-like structures—such as tags, threaded comments, or page graphs—with optimal query performance for both reads and writes. The gem provides a comprehensive API for navigating and manipulating tree relationships while maintaining data integrity.
Ruby on Rails developers who need to model hierarchical data in their applications, such as content management systems, tagging systems, or referral networks, and require high-performance tree operations.
Developers choose Closure Tree for its best-in-class query performance, concurrency safety, and rich feature set—outperforming alternatives like ancestry and awesome_nested_set while offering advanced capabilities like deterministic ordering and STI support.
Easily and efficiently make your ActiveRecord models support hierarchies
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.
Fetches ancestors, descendants, or siblings in a single SELECT query, as highlighted in the README's feature list, reducing database load for tree traversals.
Node creation requires only 2 SQL INSERTs and reparenting needs 3 operations, balancing read and write efficiency compared to alternatives like nested sets.
Uses advisory locking via with_advisory_lock to prevent data corruption in multi-threaded environments, ensuring safe concurrent writes without external tools.
Supports deterministic ordering, single-table inheritance, tree visualization with Graphviz, and nested hash retrieval, providing flexible tree manipulation out of the box.
Tightly coupled with ActiveRecord 7.2+ and Ruby on Rails, making it unsuitable for non-Rails applications or projects using older Rails versions.
Requires adding a parent_id column, generating a hierarchy table, and potentially rebuilding data with .rebuild!, which can be error-prone and time-consuming during migrations.
As admitted in the FAQ, the gem assumes single-parent hierarchies, limiting its use for more complex graph-like structures where nodes need multiple parents.
Reliance on with_advisory_lock for concurrency can introduce performance overhead and requires careful configuration, especially in multi-database or high-concurrency setups.