Two-side-polymorphic association - or: how to link multiple


#1

Hi,

I’m planning an application with a bunch of models which can be linked
to each other. Since a few days I’m thinking about the right way to go,
to implement these model associations. First thought was, I should use
polymorphic associations, but I think it’s not enough for my case. I
came up with the idea of an explicit link model which would look like
this:

LinkModel

| source_id | source_type | target_id |target_type |

There’re a few problems with this kind of association:

Every model can be a source OR a target. Let’s say I want to get every
company which is linked to a specific person (id=42), I have to do two
queries to get the ids for all companies linked to a person.

SELECT target_id FROM link_model WHERE source_type = ‘person’ AND
source_id = ‘42’ AND target_type = ‘company’
SELECT source_id FROM link_model WHERE target_type = ‘person’ AND
target_id = ‘42’ AND source_type = ‘company’

How do I implement this in Rails? This looks a bit like a
Two-Side-Polymorphic-Association. Is this possible? Or are there any
other ideas how to do this kind of association?

tisp


#2

i think this might be what you are looking for:

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


#3

Not exactly, but it’s a start. That solution is not truly two-sides, as
it only implements one of the above SQL statements. Also it’s not
really beautiful as I it could be?!

tisp