PgLtree
November 29, 2024 ยท View on GitHub
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.7
- Rails >= 5.2, < 9
- 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.