Skip to main content

How to create many subcategories in rails?

Rails • Asked by Nicolás Bobb

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


Hey @Dan,

i'm pretty curios about this, So how did you implement this on the frontend in your views like your forms?

Thanks


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.