ruby on rails - How to add a select field for non-related models in the form? -
i have 3 models. article, category , subcategory.
relations:
article belongs_to :subcategory subcategory has_many :articles subcategory belongs_to :category category has_many :subcategories
now, in form new article, want field selecting category (with ajax) add field selecting subcategory. well, first problem is, how select category when model not related article model?
if don't have special functionality in subcategories, i'd recommend use self referencial association. use ancestry gem. you'll have 2 models category
, article
class article < activerecord::base belongs_to :category end class category < activerecord::base has_ancestry has_many :articles end
it allows operate tree of categories in more convinient way:
category.roots root nodes category.ancestors_of(node) ancestors of node, node can either record or id category.children_of(node) children of node, node can either record or id category.descendants_of(node) descendants of node, node can either record or id category.subtree_of(node) subtree of node, node can either record or id category.siblings_of(node) siblings of node, node can either record or id
in form can use category.roots preselect, , after 1 of them selected use category.children_of(selected_node)
Comments
Post a Comment