我有三种模式。文章,类别和子类别。
关系:
Article belongs_to :subcategory
Subcategory has_many :articles
Subcategory belongs_to :category
Category has_many :subcategories
现在,在新文章的表单中,我想要一个用于选择类别的字段,它将(用ajax)添加另一个用于选择子类别的字段。好,第一个问题是,当该模型与Article模型无关时,如何选择类别?
如果子类别中没有任何特殊功能,建议您使用自我参照关联。使用类似祖先的宝石。您将有2个模型Category
和Article
class Article < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_ancestry
has_many :articles
end
它使您可以以更方便的方式对类别树进行操作:
Category.roots Root nodes
Category.ancestors_of(node) Ancestors of node, node can be either a record or an id
Category.children_of(node) Children of node, node can be either a record or an id
Category.descendants_of(node) Descendants of node, node can be either a record or an id
Category.subtree_of(node) Subtree of node, node can be either a record or an id
Category.siblings_of(node) Siblings of node, node can be either a record or an id
在您的表单中,您可以使用Category.roots进行预选择,然后在选择其中之一后使用Category.children_of(selected_node)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句