stefankroes / ancestry

Organise ActiveRecord model into a tree structure
MIT License
3.72k stars 458 forks source link

Ancestry with an "intermediate" model (and table) #520

Open marino-mrc opened 3 years ago

marino-mrc commented 3 years ago

Hi, it is possible to use ancestry with an "intermediate" model? I mean, I cannot modify the table where I need to use ancestry (for example User) and I'd like to use another model (like AncestryUser) in order to manage user's ancestry. It is possible? If yes, can you submit an example? Thank you

kbrock commented 3 years ago

I would not advise that. We have an intermediate table, but with a polymorphic reference to the records so your hierarchy can be with multiple records. Having said that, note that I am actively removing where possible and am not the biggest fan.

I've run into race conditions that ends up creating multiple intermediate records for a single primary record. Hardcoding the id to be the same as the primary table may get around this. Also, then the ids in the intermediate's ancestry hierarchy value would match the ids in the primary table.

I also found the bouncing through the intermediate table to take a toll on the queries.

Not sure how good your rails and SQL is, but you may be able to use sub-selects to bring back the ancestry value in a select clause and have much of what you want working. But it has the potential to be confusing and quirky.

You may want to take a look at the closure_tree gem. It's data model works closer to what you have described.