Forum: Ruby on Rails Associating with different classes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Nickolay K. (Guest)
on 2006-05-08 17:32
(Received via mailing list)
Dear Railers,

I am toying with a new project and have a schema design question.

I have a tree-like node structure. Each of the nodes will be
associated with a single object. This associated object can be of a
variety of types.

I represent the tree through a Node class which acts_as_tree. Now
imagine three other classes--Animals, Fruits and Vegetables. Each
node will have an association with one object of ONE type. The object
types are different enough to make STI impractical.

I am thinking of the following: adding a table called associations
and holding three columns--node_id, associated_type, associated_id.
Thus:

class Node < AR::B
   has_one :association
end

class Association < AR::B
   belongs_to :node
end

A method of the Association class will pull up the necessary Animal,
Fruit or Vegetable, depending on the associated_type and
associated_id. A method of the Node class will request the actual
associated object from the association itself.

Any thoughts on this?

Many thanks in advance for any ideas,
Nickolay
Josh S. (Guest)
on 2006-05-08 20:00
Nickolay K. wrote:
> Dear Railers,
>
> I am toying with a new project and have a schema design question.
>
> I have a tree-like node structure. Each of the nodes will be
> associated with a single object. This associated object can be of a
> variety of types.
>
> I represent the tree through a Node class which acts_as_tree. Now
> imagine three other classes--Animals, Fruits and Vegetables. Each
> node will have an association with one object of ONE type. The object
> types are different enough to make STI impractical.
>
> I am thinking of the following: adding a table called associations
> and holding three columns--node_id, associated_type, associated_id.

Check out polymorphism for belongs_to and has_one/has_many. It does
exactly what you describe. Look up the :polymorphic option on belongs_to
to start.

--
Josh S.
http://blog.hasmanythrough.com
Nickolay K. (Guest)
on 2006-05-09 10:52
(Received via mailing list)
> Check out polymorphism for belongs_to and has_one/has_many. It does
> exactly what you describe. Look up the :polymorphic option on
> belongs_to
> to start.

Thanks a lot for the tip Josh!

I found http://wiki.rubyonrails.org/rails/pages/
PolymorphicAssociations on the wiki and read through it. I have
written some preliminary tests and they pass as far as what I wanted
to do. :-)

Cheers!
Nickolay
This topic is locked and can not be replied to.