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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)