简体   繁体   中英

How to handle rails3 habtm with tree hierarchy (of categories)?

I've looked at the existing questions and because of variations, I cannot find a good solution on how to handle habtm with a tree hierarchy of categories. acts-as-taggable-on imposes that the code knows the contexts, which I do not want. This has been asked several times on this and other websites but truly, there has not been a complete answer yet.

Basically I have a set of categories with a single-level hierarchy:

  • Root category 1
    • Sub category 3
    • Sub category 4
  • Root category 2
    • Sub category 5
    • Sub category 6

The form part is somewhat simpler. I list all the root categories, then for each find the children. This is suitable only for single level hierarchy, and not optimal for my needs since I would rather have near infinite level (ie a solution that is indifferent to nesting level), although not necessary if it adds too much complexity.

It's mostly on the view that I am not sure how to proceed. At this point I can get a simple hash of the associated categories, but there is no hierarchy. Nested categories solutions I have seen will not work in the habtm context, rather working with the full tree itself.

OK well it was not so obvious but Ancestry (aka has_ancestry: https://github.com/stefankroes/ancestry ) manages that very well.

My model has products with categories in a HABTM relationship. The categories are a hierarchy with has_ancestry.

Once I get the product's categories, it's a simple matter of calling arrange on the collection:

@product.categories.arrange.each do |root_cats, sub_cats|

Works marvellously.

So in short, the anwer is the Ancestry gem: https://github.com/stefankroes/ancestry .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM