How to create many subcategories in rails?
Without using any gems how do I do this in rails? I see the gem Ancestry (https://github.com/stefankroes/ancestry)
Main Category
Sub Category
Sub Category
Sub-sub Category
Main Category
Sub Category
Sub-sub Category
Sub-sub-sub Category
Main Category
Sub Category
Sub Category
Sub Category
How would the relationship between models?
So firstly, I used ancestry. I found it saved me a ton of time and, well, pain. Tree structures can get really crazy depending on what you're using them for. If you really don't want to use a gem, I recommend creating a Category
model and adding a parent_id
column that can be used in a belongs_to
relation to point to it. Be aware though: things like eager loading, or even querying the full tree, in this instance get very difficult, and I'm not sure how you'd even go about those things without writing a lot of raw sql. Still, if you're really motivated, here's a nifty article on how to do that as well:
https://hashrocket.com/blog/posts/recursive-sql-in-activerecord