this is my first post in the community and a have a problema: represent a tree of categories.
First solution: each category has a reference to its parent category.
The problem with this solution is, when I want a subtree of categories I have to query the database several times, one query per level (height) of the tree and I want some solution more optimized.
Chosen solution: Category (id, name, description) and CategoryxCategory (ancestor_id, descendant_id)
And so to build a sub tree I’ll need only one query like this ,
select * from category a, categoryxcategory b.where b.ancestor_id = 1 and
b.descendant_id = a.id , gets all sub-categories of the category with id = 1.
I’ve done this solution in java using hibernate, but I could not do in Rails, how do I specify this in the migration and ActiveRecord?
Many Thanks
Can’t you just have ancestor_id and descendant_id be columns in category?
here’s a popular gem that does trees for you https://github.com/collectiveidea/awesome_nested_set