I have an array(sorted on an attribute called node_id) of ruby objects which basically needs to rendered on the front end as a tree (ul > li> ul > li …). I am using rails 2.3.8. This object is coming from the db, the structure of which might not be easily modifiable.
[#<Node node_id: 3, children: "10, 42",name: "A", weight: 45, root: true>,
#<Node node_id: 4, children: "6,88", name: "B", weight: 32, root: true]
#<Node node_id: 6, children: nil, name: "X", weight: 12, root: false>,
#<Node node_id: 7, children: "9", name: "P", weight: 98, root: true>,
#<Node node_id: 9, children: nil, name: "Q", weight: 12, root: false>,
#<Node node_id: 10, children: "23,56",name: "R", weight: 34, root: false>,
#<Node node_id: 13, children: nil, name: "T", weight: 75, root: true>,
#<Node node_id: 23, children: nil, name: "C", weight: 57, root: false>,
#<Node node_id: 42, children: nil, name: "D", weight: 25, root: false>,
#<Node node_id: 56, children: nil, name: "Y", weight: 50, root: false>
#<Node node_id: 88, children: nil, name: "W", weight: 15, root: false>]
What is the best way performance and design wise to render such a tree at the front end? This is just a sample set, the tree is not always balanced and can have hundreds of nodes.
Let’s suppose you convert children into an array of integers with the following
Then, we can index the nodes (for constant time lookup) as follows:
Or if you have the
facetsgem installed, you can just sayLet’s find the root node(s) (the ones that arent a child of anybody else)
Now we render with a recursive function
To kick things off