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?

Reply

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

Reply

Hey @Dan,

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

Thanks

Reply
Join the discussion
Create an account Log in

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

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

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.