如何处理带有树层次结构(类别)的rails3 habtm?

发布于 2024-11-03 19:03:36 字数 495 浏览 0 评论 0原文

我查看了现有的问题,由于存在差异,我找不到关于如何使用类别树层次结构处理 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓬勃野心 2024-11-10 19:03:36

好吧,这不是那么明显,但是 Ancestry(又名 has_ancestry:https://github.com/stefankroes/ancestry) 管理得很好。

我的模型包含具有 HABTM 关系的类别的产品。这些类别是具有 has_ancestry 的层次结构。

一旦我获得了产品的类别,就可以简单地调用集合上的排列:

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

效果非常好。

简而言之,答案就是 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:

@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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文