representing a graph

I am representing a graph structrure in my DB. I have a table for nodes
(which holds node names for now) and a table for segments/links. Each
segment has the id-s of its 2 end-nodes.
How do i specify this in the Rails model for a Segment ? I can't say
belongs_to twice ...
Is there a better way to do this ?

Something along these lines? This creates a directed graph, you would
just add two segments for each node pair with the source/target
reversed if you want an undirected graph.

## Models:

class Node < ActiveRecord::Base
  has_many :segments
  has_many :nodes, :through => :segments, :source => :target
end

class Segment < ActiveRecord::Base
  belongs_to :source, :class_name => "Node"
  belongs_to :target, :class_name => "Node"
end

## Migrations

create_table "nodes" do |t|
  t.column "name", :string
end
create_table "segments" do |t|
  t.column "source_id", :integer
  t.column "target_id", :integer
end

Best,

-r

Hi,