Any model which has belongs_to and has_many relation with itself can use this. It exposes a lot of ready to use methods.
gem install treeable
Once the gem is installed you can include the module for any model. You will need to specify the column which holds the parent id (default: parent_id
) and a column where Treeable will store the path (default: path
).
class User < ApplicationRecord
include Treeable
treeable_path_column :path
treeable_parent_column :parent_id
end
roots
: Get all the root elements of this classjson_tree(nodes)
: Prints all the nodes and their children.p User.json_tree(User.all) # = > [{:id=>1, :children=>[{:id=>6, :children=>[{:id=>7, :children=>[]}]}]}, {:id=>2, :children=>[{:id=>5, :children=>[]}]}, {:id=>3, :children=>[]}, {:id=>4, :children=>[]}, {:id=>5, :children=>[]}, {:id=>6, :children=>[{:id=>7, :children=>[]}]}, {:id=>7, :children=>[]}]
leaves
: Get all leaf nodes
Treeable automatically defines two associations:
parent
:belongs_to
relation to same class and return the parent nodechildren
:has_many
relation and returns all the immediate children
parent_map
: Map over all the parent nodes and executes the block providedUser.last.parent_map{|k| p k.id}
children_map
: Map over all the children node and executes the block providedUser.last.children_map{|k| p k.id}
leaf_nodes
: Returns all the leafs from this nodenodes_from_root
: Returns all the ancestors of the nodeis_leaf
: Returns wheather the node is leaf or notis_root
: Returns if the node is root or noeall_children
: Returns the list of all the children of the noderoot
: Find the root parent node
- Saurav Swaroop