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.
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.
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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.