Project

pg_ltree

0.06
Low commit activity in last 3 years
No release in over a year
Organize ActiveRecord model into a tree structure using PostgreSQL LTree
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 0
>= 0
~> 0.9.28
~> 2.4
~> 3.11

Runtime

>= 0.19, < 2
>= 5.2, < 8.0
 Project Readme

PgLtree

Gem Version Ruby Style Guide Build Status RubyDoc

Adds PostgreSQL's ltree support for ActiveRecord models

Installation

Add this line to your application's Gemfile:

gem 'pg_ltree'

And then execute:

$ bundle

Or install it yourself as:

$ gem install pg_ltree

Required

  • Ruby >= 2.0
  • Rails >= 5.2, < 8
  • Pg adapter (gem 'pg') >= 1.0, < 2

How to use

Basic usage

Enable ltree extension:

class AddLtreeExtension < ActiveRecord::Migration
  def change
    enable_extension 'ltree'
  end
end

Add column with ltree type for your model

class AddLtreePathToModel < ActiveRecord::Migration
  def change
    add_column :nodes, :path, :ltree
    add_index :nodes, :path, using: :gist
  end
end

Initialize ltree module in your model

  class Node < ActiveRecord::Base
    ltree :path
    # ltree :path, cascade_update: false # Disable cascade update
    # ltree :path, cascade_destroy: false # Disable cascade destory
    # ltree :path, cascade_update: false, cascade_destroy: false # Disable cascade callbacks
  end

Overriding ltree_scope

You can cluster trees by overriding ltree_scope. In the following example a LessonPlan can have a set of Tutorials. The tutorials in that lesson plan can be structured using a tree hierarchy.

class LessonPlan < ActiveRecord::Base
  has_many :tutorials
end

class Tutorial < ActiveRecord::Base
  belongs_to :lesson_plan

  ltree :path

  def ltree_scope
    self.class.base_class.where(lesson_plan_id:)
  end
end

Using this pattern the sibling/parent/descendent methods (as well as cascading updates and destroys) will scope to pages associated with that lesson plan. This is in contrast to Pages.all, which would be the default scope.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/sjke/pg_ltree

Changelog

See CHANGELOG for details.

License

The gem is available as open source under the terms of the MIT License.