如何处理带有树层次结构(类别)的rails3 habtm?
我查看了现有的问题,由于存在差异,我找不到关于如何使用类别树层次结构处理 habtm 的良好解决方案。 acts-as-taggable-on 强制代码知道上下文,这是我不想要的。这个问题已经在这个网站和其他网站上被问过好几次了,但实际上,还没有一个完整的答案。
基本上我有一组具有单级层次结构的类别:
- 根类别 1
- 子类别 3
- 子类别 4
- 根类别 2
- 子类别 5
- 子类别 6
表单部分稍微简单一些。我列出了所有根类别,然后为每个根类别找到子类别。这仅适用于单级层次结构,并且不是最适合我的需求,因为我宁愿拥有接近无限的级别(即与嵌套级别无关的解决方案),尽管如果它增加太多复杂性则没有必要。
主要是我不知道如何继续。此时,我可以获得关联类别的简单散列,但没有层次结构。我见过的嵌套类别解决方案在 habtm 上下文中不起作用,而是与整个树本身一起工作。
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 (i.e. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,这不是那么明显,但是 Ancestry(又名 has_ancestry:https://github.com/stefankroes/ancestry) 管理得很好。
我的模型包含具有 HABTM 关系的类别的产品。这些类别是具有 has_ancestry 的层次结构。
一旦我获得了产品的类别,就可以简单地调用集合上的排列:
效果非常好。
简而言之,答案就是 Ancestry gem:https://github.com/stefankroes/ancestry。
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:
Works marvellously.
So in short, the anwer is the Ancestry gem: https://github.com/stefankroes/ancestry.