处理类别/子类别关系的最佳方式 Ruby on Rails [英] Best way to handle Category / Subcategory relationship Ruby on Rails

查看:31
本文介绍了处理类别/子类别关系的最佳方式 Ruby on Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类别和子类别模型.类别有许多子类别,而子类别属于类别.每个子类别当前都有一个位置字段来跟踪它在所属类别下的排列位置.

I have a Category and Subcategory model. Category has many subcategories and Subcategory belongs to Category. Each subcategory currently has a position field to keep track of where it lines up under the Category it belongs to.

我这样做的方式的问题是每个我都需要 :position 字段对于每个类别都是唯一的.因此,不是在我的子类别模型中使用 validates_uniqueness_of :position,我需要一种方法来检查位置字段对其特定类别是否唯一.有没有人有任何想法,或者以前可能处理过这个问题?

The problem with the way i'm doing it is that each I need the :position field to be unique to each category. So instead of using validates_uniqueness_of :position in my Subcategory model, I need a way to check that the position field is unique to its specific Category. Anyone have any ideas, or possibly dealt with this issue before?

推荐答案

扩展 lucapettes 答案,

Expanding on lucapettes answer,

嵌套集(https://github.com/skyeagle/nested_set)是这样的:

A nested set (https://github.com/skyeagle/nested_set) is something like this :

- category
+- category 
+- category 
+--- category 
+- category 
- category
+- category 
+- category 
+--- category 
+- category

您可以在任何地方将节点添加到集合中,并将您的产品与任何类别相关联.

You can add node to the set anywhere and you would associate your product with any category.

查看此文件中的方法 https://github.com/skyeagle/nested_set/blob/master/lib/nested_set/base.rb

awsome_nested_set 的 wiki 可能有一些更好的文档,https://github.com/collectiveidea/awesome_nested_set/wiki/Awesome-nested-set-cheat-sheet

The wiki for awsome_nested_set might have some better docs, https://github.com/collectiveidea/awesome_nested_set/wiki/Awesome-nested-set-cheat-sheet

例如,您可以向左移动一个项目,(例如在这样的列表中向上移动) category.move_left

For example you can move an item left, (e.g. up in a list like this ) category.move_left

要了解此模型及其工作原理,请阅读乔塞尔科的 SQL 中的树

To understand this model and why it works, read Trees in SQL by Joe Celko

这篇关于处理类别/子类别关系的最佳方式 Ruby on Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆