Importing the language of graph databases, understand
- nodes (represented by circles),
- edges (represented by arrows), and
- properties (metadata of nodes / edges)
The graphic (courtesy of wikipedia) describes a directed graph.
What's the best way to model an undirected graph in Rails?
That is to say, a graph where all edges are reciprocal (as in above graphic), and where the properties of each edge are the same regardless of direction (contrary to above graphic).
Let's assume a default Rails 3 setup using a sql store via ActiveRecord.
A double polymorphic association would create a directed graph, able to model the data described by the above image.
def Edge < ActiveRecord::Base
belongs_to :head, polymorphic: true
belongs_to :tail, polymorphic: true
end
class Node < ActiveRecord::Base
has_many :from, as: :head
has_many :to, as: :tail
end
class Group < ActiveRecord::Base
# a Node of Type: Group
has_many :from, as: :head
has_many :to, as: :tail
end
Should one extend this model to manage inverse relationships, or is a better model available?
One element of an app may be a graph problem, but it does not mean the app is centered around the problem, that graph transversals must be performed on the data, nor that the dataset is larger than available memory.