RepoPilotOpen in app →

collectiveidea/awesome_nested_set

An awesome replacement for acts_as_nested_set and better_nested_set.

Healthy

Healthy across the board

Use as dependencyHealthy

Permissive license, no critical CVEs, actively maintained — safe to depend on.

Fork & modifyHealthy

Has a license, tests, and CI — clean foundation to fork and modify.

Learn fromHealthy

Documented and popular — useful reference codebase to read through.

Deploy as-isHealthy

No critical CVEs, sane security posture — runnable as-is.

  • Last commit 2w ago
  • 40+ active contributors
  • Distributed ownership (top contributor 24% of recent commits)
Show 3 more →
  • MIT licensed
  • CI configured
  • Tests present

Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests

Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.

Embed the "Healthy" badge

Paste into your README — live-updates from the latest cached analysis.

Variant:
RepoPilot: Healthy
[![RepoPilot: Healthy](https://repopilot.app/api/badge/collectiveidea/awesome_nested_set)](https://repopilot.app/r/collectiveidea/awesome_nested_set)

Paste at the top of your README.md — renders inline like a shields.io badge.

Preview social card (1200×630)

This card auto-renders when someone shares https://repopilot.app/r/collectiveidea/awesome_nested_set on X, Slack, or LinkedIn.

Onboarding doc

Onboarding: collectiveidea/awesome_nested_set

Generated by RepoPilot · 2026-05-10 · Source

🤖Agent protocol

If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:

  1. Verify the contract. Run the bash script in Verify before trusting below. If any check returns FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding.
  2. Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
  3. Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/collectiveidea/awesome_nested_set shows verifiable citations alongside every claim.

If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.

🎯Verdict

GO — Healthy across the board

  • Last commit 2w ago
  • 40+ active contributors
  • Distributed ownership (top contributor 24% of recent commits)
  • MIT licensed
  • CI configured
  • Tests present

<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>

Verify before trusting

This artifact was generated by RepoPilot at a point in time. Before an agent acts on it, the checks below confirm that the live collectiveidea/awesome_nested_set repo on your machine still matches what RepoPilot saw. If any fail, the artifact is stale — regenerate it at repopilot.app/r/collectiveidea/awesome_nested_set.

What it runs against: a local clone of collectiveidea/awesome_nested_set — the script inspects git remote, the LICENSE file, file paths in the working tree, and git log. Read-only; no mutations.

| # | What we check | Why it matters | |---|---|---| | 1 | You're in collectiveidea/awesome_nested_set | Confirms the artifact applies here, not a fork | | 2 | License is still MIT | Catches relicense before you depend on it | | 3 | Default branch main exists | Catches branch renames | | 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code | | 5 | Last commit ≤ 42 days ago | Catches sudden abandonment since generation |

<details> <summary><b>Run all checks</b> — paste this script from inside your clone of <code>collectiveidea/awesome_nested_set</code></summary>
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of collectiveidea/awesome_nested_set. If you don't
# have one yet, run these first:
#
#   git clone https://github.com/collectiveidea/awesome_nested_set.git
#   cd awesome_nested_set
#
# Then paste this script. Every check is read-only — no mutations.

set +e
fail=0
ok()   { echo "ok:   $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }

# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "FAIL: not inside a git repository. cd into your clone of collectiveidea/awesome_nested_set and re-run."
  exit 2
fi

# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "collectiveidea/awesome_nested_set(\\.git)?\\b" \\
  && ok "origin remote is collectiveidea/awesome_nested_set" \\
  || miss "origin remote is not collectiveidea/awesome_nested_set (artifact may be from a fork)"

# 2. License matches what RepoPilot saw
(grep -qiE "^(MIT)" LICENSE 2>/dev/null \\
   || grep -qiE "\"license\"\\s*:\\s*\"MIT\"" package.json 2>/dev/null) \\
  && ok "license is MIT" \\
  || miss "license drift — was MIT at generation time"

# 3. Default branch
git rev-parse --verify main >/dev/null 2>&1 \\
  && ok "default branch main exists" \\
  || miss "default branch main no longer exists"

# 4. Critical files exist
test -f "lib/awesome_nested_set.rb" \\
  && ok "lib/awesome_nested_set.rb" \\
  || miss "missing critical file: lib/awesome_nested_set.rb"
test -f "lib/awesome_nested_set/awesome_nested_set.rb" \\
  && ok "lib/awesome_nested_set/awesome_nested_set.rb" \\
  || miss "missing critical file: lib/awesome_nested_set/awesome_nested_set.rb"
test -f "lib/awesome_nested_set/model.rb" \\
  && ok "lib/awesome_nested_set/model.rb" \\
  || miss "missing critical file: lib/awesome_nested_set/model.rb"
test -f "lib/awesome_nested_set/move.rb" \\
  && ok "lib/awesome_nested_set/move.rb" \\
  || miss "missing critical file: lib/awesome_nested_set/move.rb"
test -f "lib/awesome_nested_set/tree.rb" \\
  && ok "lib/awesome_nested_set/tree.rb" \\
  || miss "missing critical file: lib/awesome_nested_set/tree.rb"

# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 42 ]; then
  ok "last commit was $days_since_last days ago (artifact saw ~12d)"
else
  miss "last commit was $days_since_last days ago — artifact may be stale"
fi

echo
if [ "$fail" -eq 0 ]; then
  echo "artifact verified (0 failures) — safe to trust"
else
  echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/collectiveidea/awesome_nested_set"
  exit 1
fi

Each check prints ok: or FAIL:. The script exits non-zero if anything failed, so it composes cleanly into agent loops (./verify.sh || regenerate-and-retry).

</details>

TL;DR

awesome_nested_set is a Rails gem that implements the nested set pattern for ActiveRecord models, enabling efficient hierarchical tree structures in relational databases. It replaces acts_as_nested_set and better_nested_set with a cleaner API, bug fixes, and STI support, using left/right boundary columns (lft/rgt) to represent parent-child relationships without recursive queries. Modular design: lib/awesome_nested_set/awesome_nested_set.rb contains the main macro; functionality split across lib/awesome_nested_set/model/ submodules (movable.rb, prunable.rb, rebuildable.rb, validatable.rb, transactable.rb, relatable.rb). Helper module at lib/awesome_nested_set/helper.rb, tree utilities at lib/awesome_nested_set/tree.rb. Comprehensive test suite mirrors structure in spec/awesome_nested_set/.

👥Who it's for

Rails developers building hierarchical data structures (org charts, category trees, comment threads) who need efficient querying and manipulation of nested trees without N+1 query problems or complex recursive logic.

🌱Maturity & risk

Actively maintained and production-ready. The gem supports Rails 5.2 through 8.1 (evident from gemfiles/rails_*.gemfile entries), has comprehensive CI setup (.github/workflows/ci.yml), includes extensive test fixtures (spec/fixtures/), and maintains an active changelog. Multiple Rails versions tested indicates stable, battle-tested code.

Low risk for Rails applications within supported versions. Single-maintainer gem (collectiveidea) but with long history and established community adoption as a successor to popular gems. Risk surface is narrow: requires exact schema (lft, rgt, parent_id columns) and database transactions for safety. No heavy external dependencies visible in structure.

Active areas of work

Actively supporting recent Rails versions (Rails 8.1 gemfile added, CI workflows in place). Gem publishes via GitHub Actions (.github/workflows/publish_gem.yml). Repository uses Appraisals for multi-version Rails testing. No breaking changes apparent from changelog structure—incremental improvements and version compatibility work.

🚀Get running

git clone https://github.com/collectiveidea/awesome_nested_set.git && cd awesome_nested_set && bundle install && bundle exec rake

Daily commands: bundle exec rake (runs default Rake task, likely tests); bundle exec appraisal install && bundle exec appraisal rails_8_1 rake (test against specific Rails version)

🗺️Map of the codebase

  • lib/awesome_nested_set.rb — Main entry point that loads all nested set functionality; every contributor must understand how the gem initializes.
  • lib/awesome_nested_set/awesome_nested_set.rb — Core mixin that applies nested set behavior to models; defines the DSL and primary API surface.
  • lib/awesome_nested_set/model.rb — Central model module orchestrating all nested set operations and database state management.
  • lib/awesome_nested_set/move.rb — Encapsulates the complex logic for moving nodes within the tree structure and maintaining lft/rgt values.
  • lib/awesome_nested_set/tree.rb — Query builder and tree traversal abstraction; essential for understanding how the nested set is queried.
  • spec/awesome_nested_set_spec.rb — Primary test suite demonstrating all public API contracts and expected behavior.

🧩Components & responsibilities

  • AwesomeNestedSet Mixin (Active) — Entry point DSL; configures column names, applies validations, and wires associations

🛠️How to make changes

Add nested set to a new Rails model

  1. Create migration with lft, rgt, parent_id, depth, and children_count columns on your model table (spec/db/schema.rb)
  2. Add act_as_nested_set macro to your model class, optionally configuring column names via scope (lib/awesome_nested_set/awesome_nested_set.rb)
  3. Call Model.rebuild! to initialize the nested set structure from parent_id relationships (lib/awesome_nested_set/model/rebuildable.rb)

Move a node in the tree

  1. Call node.move_to_child_of(parent_node) or node.move_to_left_of(sibling) on the node instance (lib/awesome_nested_set/model/movable.rb)
  2. The move! method updates lft/rgt bounds and recalculates ancestor depths within a transaction (lib/awesome_nested_set/move.rb)
  3. Optionally wrap in a transaction block using Model.with_nested_set_update { node.move_to_child_of(...) } (lib/awesome_nested_set/model/transactable.rb)

Query tree relationships efficiently

  1. Use scopes like node.ancestors, node.descendants, node.self_and_descendants to fetch related nodes (lib/awesome_nested_set/tree.rb)
  2. Scopes leverage lft/rgt range queries for O(1) index lookups instead of traversing parent_id chains (lib/awesome_nested_set/model.rb)
  3. Chain scopes: Model.where(active: true).descendants_of(node) to apply additional filters (lib/awesome_nested_set/tree.rb)

Render a tree in a view

  1. Use the nested_set_options helper to build a select dropdown with indentation based on node depth (lib/awesome_nested_set/helper.rb)
  2. Or iterate manually: @root.traverse_with_order { |node, depth| ... } for custom rendering (lib/awesome_nested_set/iterator.rb)
  3. See example usage in spec/awesome_nested_set/helper_spec.rb for Rails view integration patterns (spec/awesome_nested_set/helper_spec.rb)

🔧Why these technologies

  • Nested Set Algorithm (lft/rgt) — Enables O(1) ancestor/descendant queries via index-backed range scans; avoids recursive CTEs and hierarchical traversal overhead
  • ActiveRecord Callbacks & Scopes — Integrates seamlessly with Rails models; leverages existing validation and association hooks for consistency
  • Database Transactions — Ensures nested set invariants (lft < rgt, gaps indicate parent-child relationships) remain valid even during concurrent modifications
  • STI Support — Allows subclasses to inherit nested set behavior, enabling polymorphic tree structures within a single table

⚖️Trade-offs already made

  • Use lft/rgt instead of parent_id-only hierarchies

    • Why: Ancestor/descendant queries require O(log n) recursive lookups with parent_id; lft/rgt trades write complexity for read speed
    • Consequence: Node movements require recalculating lft/rgt for all affected nodes; less efficient for forests with frequent deep moves
  • Require explicit depth and children_count columns

    • Why: Caching depth/count avoids expensive COUNT(*) and recursion on every query
    • Consequence: Adds maintenance burden; must keep columns in sync via callbacks and rebuild operations
  • Immutable scope method chains

    • Why: Avoids side effects and allows clean composition of queries (node.ancestors.where(active: true))
    • Consequence: Queries must be re-evaluated if scope changes; no in-memory caching of tree relationships
  • Validate tree integrity via set_validator

    • Why: Detects silent data corruption due to concurrent updates or bugs
    • Consequence: Validation is O(n); expensive to run on large trees; typically called only during maintenance windows

🚫Non-goals (don't propose these)

  • Real-time multi-database replication or eventual consistency (assumes single authoritative database)
  • Horizontal sharding of tree data (designed for single-table nested sets)
  • Zero-downtime schema migrations (requires rebuild! after adding nested set columns)
  • Automatic conflict resolution in concurrent move operations (uses pessimistic locking via transactions)

🪤Traps & gotchas

Schema must include lft/rgt columns (integer, not null, indexed) or movable.rb will fail silently. children_count column requires null: false, default: 0 or incrementing breaks. depth column optional but improves query performance. Database transactions essential for consistency—use transactable.rb or wrap in explicit transactions. Scoped trees (scope: option) require underscore-suffixed foreign key (e.g., scope: :notable becomes notable_id). Parent self-reference validation (cycles) not prevented by default—use validatable.rb.

🏗️Architecture

💡Concepts to learn

  • Nested Set Model (Lft/Rgt boundaries) — Core algorithm underlying this gem—you must understand how lft/rgt encode parent-child relationships without parent_id to debug tree corruption or optimize queries
  • NLPO (Nested Lineage Positional Offset) — Variant of nested set used here; enables efficient range queries and depth calculation via Lft/Rgt pairs
  • ActiveRecord Macro Pattern — acts_as_nested_set uses macros to inject methods into models at class definition time; understanding this Rails pattern is key to extending the gem
  • Single Table Inheritance (STI) — Gem explicitly supports STI; understanding how subclasses share a table with type column is essential for avoiding tree corruption across inheritance hierarchies
  • Database Transaction Atomicity — lib/awesome_nested_set/model/transactable.rb wraps tree operations in transactions; race conditions can corrupt Lft/Rgt boundaries without proper locking
  • Materialized Path vs. Nested Set Trade-offs — Nested set excels at subtree queries but struggles with node insertion; understanding when to choose Lft/Rgt vs. path-based trees (e.g., '/1/2/3/') informs schema design
  • rails/rails — ActiveRecord is the dependency layer this gem integrates with; understanding AR's query builder essential
  • mongoid/mongoid-tree — Alternative nested set implementation for MongoDB—useful to understand why RDBMS-specific Lft/Rgt algorithm is needed
  • kaminari/kaminari — Common companion gem for paginating large nested sets when rendering tree results
  • collectiveidea/acts-as-list — Sibling gem from same maintainer; similar pattern for flat ordered lists (contrasts with hierarchical trees)
  • eparreno/ancestry — Alternative tree gem using materialized_path pattern instead of Lft/Rgt; good for understanding trade-offs

🪄PR ideas

To work on one of these in Claude Code or Cursor, paste: Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.

Add comprehensive test coverage for lib/awesome_nested_set/model/movable.rb

The movable.rb module handles critical tree manipulation operations (moving nodes left/right/into/out of parents). Currently, spec/awesome_nested_set/model/ only has transactable_spec.rb. The movable functionality deserves dedicated unit tests covering edge cases like moving to invalid positions, circular references, and scope boundaries.

  • [ ] Create spec/awesome_nested_set/model/movable_spec.rb
  • [ ] Add tests for move_left, move_right, move_to_child_of, move_to_root operations
  • [ ] Add edge case tests: moving to self, moving to descendants, boundary conditions
  • [ ] Test interaction with scoped models using the fixtures in spec/fixtures/

Add comprehensive test coverage for lib/awesome_nested_set/model/rebuildable.rb

The rebuildable.rb module handles tree reconstruction, which is critical infrastructure for maintaining nested set integrity. There are no dedicated tests for this module. This is a high-risk area that needs thorough validation across the multiple gemfile Rails versions (5.2 through 8.1).

  • [ ] Create spec/awesome_nested_set/model/rebuildable_spec.rb
  • [ ] Add tests for rebuild method with various tree structures (flat, deep, branched)
  • [ ] Add tests for rebuild with scoped models and STI models
  • [ ] Test rebuild behavior after destructive operations (deletions, orphaning nodes)

Add integration tests for STI (Single Table Inheritance) support mentioned in README

The README explicitly states 'adds STI support' as a key feature, but there are no dedicated STI test fixtures or test cases in spec/fixtures/ or spec/models/. This is a documented feature that lacks test validation across the 9 supported Rails versions in gemfiles/.

  • [ ] Create spec/fixtures/sti_models.yml with parent and child STI model records
  • [ ] Create spec/models/sti_models_spec.rb testing nested set behavior with inheritance
  • [ ] Add tests verifying that STI child classes maintain separate or shared nested set trees appropriately
  • [ ] Test STI interaction with scoping and validation in lib/awesome_nested_set/model/validatable.rb

🌿Good first issues

  • Add specs for edge cases in lib/awesome_nested_set/model/relatable.rb (ancestors, descendants, siblings with STI models) to match test coverage of movable.rb
  • Expand lib/awesome_nested_set/helper.rb view helpers with examples in spec/awesome_nested_set/helper_spec.rb—currently only 1 helper tested
  • Create migration/schema documentation for the 5 optional field combinations (depth, children_count, both, neither, custom names) with working spec/db/schema.rb examples

Top contributors

Click to expand

📝Recent commits

Click to expand
  • 7a64274 — Merge pull request #500 from MattRogish/fix-frozen-string-literal-warning (danielmorrison)
  • c55403f — Update CHANGELOG for frozen string literal fix (MattRogish)
  • 4e512bb — Fix frozen string literal warning in scope_for_rebuild (MattRogish)
  • 2196184 — Set version to 3.9.0 for release (parndt)
  • 7de9441 — Add Ruby 3.4 consistently and fix excludes (#498) (parndt)
  • 111c3f8 — Add Rails 8.1 support (#495) (caonUlisses)
  • 9649a3b — CI: bump actions/checkout from v3/v4 to v6 (#494) (tnir)
  • 04c580e — Remove rails_main from CI workflow, and pry dependency (#497) (parndt)
  • 3d32141 — Remove gem cert chain to use Trusted Publishing (danielmorrison)
  • 276a472 — Merge pull request #490 from collectiveidea/trusted-publishing (danielmorrison)

🔒Security observations

This is a well-structured Ruby gem for nested set implementations. The main security concerns are typical for ORMs: potential SQL injection in tree operations, XSS in view helpers, and race conditions in concurrent scenarios. The absence of actual code review and missing dependency lock file prevents deeper analysis. The gem appears to follow Rails conventions well, but runtime behavior validation is needed. Recommend: (1) Run 'bundle audit' on dependencies, (2) Conduct code review of query construction in movable.rb and tree.rb, (3) Test helpers for XSS with special characters, (4) Add concurrency tests.

  • Medium · Potential SQL Injection in Nested Set Operations — lib/awesome_nested_set/model/movable.rb, lib/awesome_nested_set/tree.rb, lib/awesome_nested_set/move.rb. The codebase implements nested set pattern with tree traversal operations. Files like lib/awesome_nested_set/model/movable.rb, lib/awesome_nested_set/tree.rb, and lib/awesome_nested_set/move.rb likely contain dynamic SQL query construction. Without seeing the actual code, there's risk of SQL injection if user input is directly interpolated into where clauses for lft/rgt column updates. Fix: Ensure all database queries use parameterized queries/prepared statements. Use ActiveRecord's built-in query methods (where, update_all with proper parameter binding) rather than string interpolation. Audit any raw SQL for user input handling.
  • Medium · Missing Dependency Lock File — Gemfile (dependency specification missing). No Gemfile.lock or package-lock.json content was provided. This makes it impossible to verify if dependencies have known security vulnerabilities or if versions are pinned properly. Fix: Ensure Gemfile.lock is committed to version control and regularly run 'bundle audit' or 'bundler-audit' to check for known vulnerabilities in dependencies. Keep dependencies up to date.
  • Low · Helper Output Potential XSS Vector — lib/awesome_nested_set/helper.rb. The presence of lib/awesome_nested_set/helper.rb suggests view helpers that may output nested tree structures. If these helpers output user-provided data without proper HTML escaping, XSS vulnerabilities could exist. Fix: Ensure all helper methods use ActiveRecord's html_safe sparingly and only on pre-sanitized content. Use Rails tag helpers and ensure user input is automatically escaped. Test with XSS payloads in category/node names.
  • Low · Insufficient Input Validation in Tree Operations — lib/awesome_nested_set/model/validatable.rb, lib/awesome_nested_set/model/movable.rb. lib/awesome_nested_set/model/validatable.rb exists but specific validation rules are unknown. Nested set operations (move, insert, delete) could be vulnerable to logic errors if parent/child relationships aren't properly validated. Fix: Implement comprehensive validation for: circular reference prevention (node cannot be moved to its own descendant), proper lft/rgt boundary checks, and parent-child relationship integrity. Add tests for edge cases.
  • Low · Potential Race Condition in Concurrent Operations — lib/awesome_nested_set/model/transactable.rb, lib/awesome_nested_set/model/rebuildable.rb. lib/awesome_nested_set/model/transactable.rb suggests transaction handling. Nested set updates require careful locking to prevent race conditions when multiple concurrent requests modify the tree structure. Fix: Ensure pessimistic locking (lock!) is used during tree mutations. Use database-level transactions with appropriate isolation levels. Test concurrent move operations to verify no data corruption occurs.

LLM-derived; treat as a starting point, not a security audit.


Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.

Healthy signals · collectiveidea/awesome_nested_set — RepoPilot