mceachen/closure_tree: Easily and efficiently make your ActiveRecord models support hierarchies

Updated . Posted . Visible to the public.

Closure_tree Show archive.org snapshot lets your ActiveRecord models act as nodes in a tree data structure.

This promises a few improvements over the battle-tested ancestry Show archive.org snapshot gem, such as:

  • Better performance
  • Pre-ordered trees (painful to do with ancestry)
  • Holds a mutex during tree manipulations (an issue with ancestry, where concurrent updates can cause deadlocks and corrupt data).

It has some more moving parts than ancestry though (see below).

Implementation

It does not use a ancestry column, but a parent_id column plus an extra table per model:

add_column :users, :parent_id, :integer

create_table :user_hierarchies, id: false do |t|
  t.integer :ancestor_id, null: false
  t.integer :descendant_id, null: false
  t.integer :generations, null: false
end

This is enough to implement common read-operations like "get all descendants" with a single SELECT.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2016-11-08 13:41)