Multiple polymorphism?


#1

Hello all,

Let me explain a fairly complex problem, I am blocked
and if someone could give me a boost I can thank him
enough!

The concept:

I have a series of tables in DB (users, functions, expertize, …)

I want to put in place a system that would allow me to link these
different objects between them in a very flexible one
table.

My idea:

Create a table “objectrelations” containing the following fields:

id
linkfrom_id
linkfrom_type
linkto_id
linkto_type
created_at
updated_at
stopped_at

1 record objectrelations:

id: 1
linkfrom_id: 1 # User ID = 1
linkfrom_type: “User”
linkto_id: 1 # expertize ID = 1
linkto_type: “expertize”
created_at: now ()
updated_at: now ()
stopped_at: NULL

The problem:

This works well in DB, it allows me to create links between
different objects, back links, to end a relationship
(via the column stopped_at) without removing the link DB (it keeps a
history) …

As against, I don’t find how to implement this model in
Rails (in models).

I think I understand that I will use the polymorphism,
the “Through Associations” or “Single table inheritance” but I don’t
know how.

I looked at the side of “acts_as_taggable”, they use a system
similar but only in one direction (any object ->
tags). Unfortunately, here I must be able to link anything with
anything …

Does anyone have an idea to help me? How should I do this ?

Thank you


#2

Maybe I’m missing something, but it doesn’t sound like you need
acts_as_taggable or single table inheritance. I think you will get the
desired result by setting up the ObjectRelations model as follows:

class ObjectRelations < ActiveRecord::Base
belongs_to :linkfrom, :polymorphic => true
belongs_to :linkto, :polymorphic => true
end

class User < ActiveRecord::Base
has_many :objectrelations, :as => :linkto
has_many :objectrelations, :as => :linkfrom
end

On Dec 8, 5:39 am, Vincenzo Ruggiero <rails-mailing-l…@andreas-


#3

Andrew B. wrote:

Maybe I’m missing something, but it doesn’t sound like you need
acts_as_taggable or single table inheritance. I think you will get the
desired result by setting up the ObjectRelations model as follows:

class ObjectRelations < ActiveRecord::Base
belongs_to :linkfrom, :polymorphic => true
belongs_to :linkto, :polymorphic => true
end

class User < ActiveRecord::Base
has_many :objectrelations, :as => :linkto
has_many :objectrelations, :as => :linkfrom
end

On Dec 8, 5:39�am, Vincenzo Ruggiero <rails-mailing-l…@andreas-

Agreed…

http://wiki.rubyonrails.org/rails/pages/ManytoManyPolymorphicAssociations