All threads / How to create many subcategories in rails?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to create many subcategories in rails?

Nicolás Bobb asked 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

Hey @Dan,

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

Thanks

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,344+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.