Read more

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

Henning Koch
November 08, 2016Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2016-11-08 14:41)