TreeStructure
Tree Structure allows the records of a ActiveRecord model to be organized in a tree structure.
Installation
Add this line to your application's Gemfile:
gem 'tree_structure'
And then execute:
$ bundle install
Or install it yourself as:
$ gem install tree_structure
Development
After installing the tree_structure gem in your Gemfile, follow these steps to set up the tree structure:
Add a
parent_idcolumn to the table where you want to organize the tree structure. You can do this by creating a migration:class AddParentIdToYourModel < ActiveRecord::Migration[6.0] def change add_column :your_model_name, :parent_id, :integer add_index :your_model_name, :parent_id end endInclude the TreeStructure module in the model that will be organized in a tree structure. For example:
class YourModelName < ApplicationRecord include TreeStructure endRun your migrations to update the database schema:
rails db:migrate
Example Usage
Once you have set up your model, you can start using the tree structure features. For example:
Create root nodes
root1 = YourModelName.create(name: 'Root 1')
root2 = YourModelName.create(name: 'Root 2')
Create child nodes
child1 = YourModelName.create(name: 'Child 1', parent: root1)
child2 = YourModelName.create(name: 'Child 2', parent: root1)
child3 = YourModelName.create(name: 'Child 3', parent: root2)
Identify root nodes
root1.root? #true
child1.root? #false
Identify leaf nodes
root1.leaf? #false
child1.leaf? #true
Find ancestors
child1.ancestors
Find descendants(will return descendants)
root1.descendants
Find subtree(will return subtree)
root1.subtree
Other nodes with same parent
child1.siblings
Root to child path
child1.path_to_root
Root to child depth
child2.depth
Nodes without children
root1.leaves
Root to child depth
child2.move_to_child_of root1
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/tree_structure.
License
The gem is available as open source under the terms of the MIT License.