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 ?

Thanks

Self referential has_many :through, with the segment as the join model?

-faisal

On Dec 17, 8:16 pm, hapciu [email protected] wrote:

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,

On Dec 17, 8:16 pm, hapciu [email protected] wrote:

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 ?

Mybe you 'd like to have a look on nestedset theory and our
implementation as plugin.
Thanks to some devs that helped a lot, our plugin has many tests and
begins to work well.

Jean-Christophe M.

Better Nested Set for rails:
http://opensource.symetrie.com/trac/better_nested_set