1

在我的 mongodb/rails 项目中,我有类别和子类别。两者都使用相同的模型类别。每个子类别可以属于多个类别,类别也可以有多个子类别。

现在我不知道如何编码这种与模型的关系,因为我在两边都有相同的模型类别。我也欢迎一些示例,如何在 rails 中对 Category 的表单视图进行编码,以便能够将子类别添加到类别中。

我使用 mongoid 2.4,rails 3.2.7。

4

1 回答 1

0

你想在has_and_belongs_to_many这里建立关系:

has_and_belongs_to_many :child_categories, class_name: "Category", inverse_of: :parent_categories
has_and_belongs_to_many :parent_categories, class_name: "Catgeory", inverse_of: child_categories

一个用例:

film_category1 = Category.create(name: "French")
film_category2 = Category.create(name: "Spanish")
film_category3 = Category.create(name: "Romantic")
film_category1.child_categories << film_category3
film_category2.child_categories << film_category3

film_category3.parent_categories # [film_category1, film_category2]
film_category2.child_categories # [film_category3]

等等

于 2012-08-18T14:12:05.283 回答