Adds PostgreSQL's ltree support for ActiveRecord
models
Add this line to your application's Gemfile:
gem 'pg_ltree'
And then execute:
$ bundle
Or install it yourself as:
$ gem install pg_ltree
- Ruby >= 2.7
- Rails >= 5.2, < 9
- Pg adapter (gem 'pg') >= 1.0, < 2
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
You can cluster trees by overriding ltree_scope
. In the following example a LessonPlan
can have a set of Tutorial
s. 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.
Bug reports and pull requests are welcome on GitHub at https://github.com/sjke/pg_ltree
See CHANGELOG for details.
The gem is available as open source under the terms of the MIT License.