I have a data structure that I’m looking to model and persist in rails. It’s self-referential and would look a lot like a hierarchical tree however instead of having just one parent each node could have multiple parents and multiple children.
It might look something like this (all nodes are the same model):
Foo Bonk
| | | |
Bar Baz Foo Bork
| |
Baz Bork
Where all of the nodes with the same name are actually the same node.
I also want to find all instances of the model that contain a certain “ingredient.”
The closest thing I found was https://github.com/mceachen/closure_tree but as far as I can tell each node only has one parent.
I’m ideally looking for a pattern to implement with ActiveRecord, but will consider any solution.
For each node having only one parent, this is a good way to do it:
As you can tell, its an ActiveRecord model with a field named parent_id pointing to the parent node.
For multiple parents, this can be extended to create a many-to-many self referential join.
Create the join table, now you should be able to do Node.children and Node.nodes for parents.
Note: The second part has not been tested, but let me know if it doesn’t work.