# representing a graph

**URL:** <https://discuss.rubyonrails.org/t/representing-a-graph/5998>\
**Category:** rubyonrails-talk\
**Created:** [December 18, 2006, 2:01pm UTC](https://discuss.rubyonrails.org/t/representing-a-graph/5998 "2006-12-18T14:01:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ryan.raaum](https://avatars.discourse-cdn.com/v4/letter/r/97f17d/32.png) [@ryan.raaum](https://discuss.rubyonrails.org/u/ryan.raaum)\
**Post date:** [December 18, 2006, 2:01pm UTC](https://discuss.rubyonrails.org/t/representing-a-graph/5998/1 "2006-12-18T14:01:58Z")

</div>

> 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 &nbsp;&nbsp;has\_many :segments &nbsp;&nbsp;has\_many :nodes, :through =\> :segments, :source =\> :target end

class Segment \< ActiveRecord::Base &nbsp;&nbsp;belongs\_to :source, :class\_name =\> "Node" &nbsp;&nbsp;belongs\_to :target, :class\_name =\> "Node" end

## Migrations

create\_table "nodes" do |t| &nbsp;&nbsp;t.column "name", :string end create\_table "segments" do |t| &nbsp;&nbsp;t.column "source\_id", :integer &nbsp;&nbsp;t.column "target\_id", :integer end

Best,

-r

---

<div class="post-metadata">

**Author:** ![Jean-Christophe\_Mich](https://avatars.discourse-cdn.com/v4/letter/j/49beb7/32.png) [@Jean-Christophe\_Mich](https://discuss.rubyonrails.org/u/Jean-Christophe_Mich)\
**Post date:** [December 18, 2006, 3:19pm UTC](https://discuss.rubyonrails.org/t/representing-a-graph/5998/2 "2006-12-18T15:19:01Z")

</div>

Hi,
