Friday, December 24, 2010

[Rails] Re: Active Record Relations and Nesting

On Dec 22, 11:16 pm, Devin M <devin...@gmail.com> wrote:
> Hello,
>   I am looking to create a rails app that will model and display
> related nodes. I am just beginning to dive into active record and I
> was wondering if the following pesudo code would work?
>
> class NodeLink < ActiveRecord::Base
>   belongs_to :node # foreign key - node_id (recorded as
> primary_node_id)
>   belongs_to :node # foreign key - node_id (recorded as
> secondary_node_id)
> end

You'll need to specify different names for these two associations; a
working declaration might look like:

class NodeLink < ActiveRecord::Base
belongs_to :primary_node, :class_name => 'Node'
belongs_to :secondary_node, :class_name => 'Node'
end

> class Node < ActiveRecord::Base
>   has_many :nodes, :through => :node_links
> end

This gets messier:

class Node < ActiveRecord::Base
has_many :primary_links, :foreign_key =>
'primary_node_id', :class_name => 'NodeLink'
has_many :secondary_links, :foreign_key =>
'secondary_node_id', :class_name => 'NodeLink'
has_many :primary_nodes, :through => :primary_links, :source
=> :secondary_node
has_many :secondary_nodes, :through => :secondary_links, :source
=> :primary_node
end

This offers some additional detail:

http://stackoverflow.com/questions/578084/how-to-implement-undirected-graph-in-ruby-on-rails

Note that it's going to be fairly complicated to deal with "all nodes
that are connected to this one" unless you denormalize somewhat and
make *two* NodeLinks for each edge. You may want to consider if you
*really* need a completely undirected graph, or if there's additional
structure (tree-like behavior, for instance) that you can simplify
things with.

If this is a central concern to your app, you may want to look into
the specialized "graph databases" that are now available.

--Matt Jones

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate