Directed graph by "has_many through"
My model will be called Node, and I want to connect them with other nodes in a way that is called “directed graph”.
An example of a directed graph from Wikimedia Commons.
Each node can have zero, one or many children, and zero, one or many parents. To do this I need an another model which will represent connections between nodes. I assume that Node model already exists and I will create the NodeConnection model by generating a scaffold.
rails g scaffold NodeConnection child:references parent:references --no-stylesheets
Nodes will be connected with other nodes, but I can’t make two column with the same “node” name. Instead of that the names are “child” and “parent”. I think the same result can be achived by
child_id:integer parent_id:integer instead of
An auto-generated migration is OK, I don’t need to add anything at this moment, so I can migrate.
The associations in the NodeConnection model file should have additional arguments.
class NodeConnection < ActiveRecord::Base belongs_to :parent, class_name: 'Node', foreign_key: 'parent_id' belongs_to :child, class_name: 'Node', foreign_key: 'child_id' end
And an assiociation in the Node model file:
class Node < ActiveRecord::Base has_many :parent_connections, foreign_key: 'child_id', class_name: 'NodeConnection' has_many :parents, through: :parent_connections has_many :child_connections, foreign_key: 'parent_id', class_name: 'NodeConnection' has_many :children, through: :child_connections end
For each node there are now methods