What’s the best way to handle parent child relationships?
Here’s the scenario:
Categories have_many SubCategories (They are separate models for a specific reason that isn’t relevant here)
SubCategories can have n SubSubCategories (Where SubCategory is the parent and subcategories are an infinite number of children.) SubSubCategories can have an infinite number of SubSubSubCategories and SubSubSubCategories can have an infinite number of Items. However, any of these subcategories can also not have children and just have an Item.
Categories will always have at least 1 SubCategory. A SubCategory could have SubSubs or not. A SubCategory that has a SubSub will not have an Item. A SubCategory that does not have a SubSub will always have at least one Item.
So I’m thinking three models are needed:
The Category (which has different DB fields than the Subs so it will need it’s own model)
The SubCategory
The Item
I’m thinking SubCategory can belong to Category and would have a category_id field. A SubCategory would also have_many Subcategories (perhaps has_many :children, class_name: 'SubCategory"
) And in that same model there’d be a has_one :parent, class_name: 'SubCategory', foreign_key: parent_id
If the parent_id is nil, then it would be the top SubCategory.
Does this work?