Parent Child relationships

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?

@briandear, before you code a complicated data structure, do you know how likely it is that the hierarchy will gain or lose a level at some point in the future? You might want to try to use fewer classes but tie their hierarchy together with something like the GitHub - amerine/acts_as_tree: ActsAsTree -- Extends ActiveRecord to add simple support for organizing items into parent–children relationships. gem.

Thanks Geoff! I’m looking at acts_as_tree as well as Ancestry and one of my buddies recommended that this might be a self-referencing table. But you definitely got me into a better place.