Forum: Ruby on Rails Two-side-polymorphic association - or: how to link multiple

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.
tisp (Guest)
on 2007-01-11 13:52
(Received via mailing list)
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
Chris H. (Guest)
on 2007-01-19 17:31
(Received via mailing list)
i think this might be what you are looking for:

http://wiki.rubyonrails.org/rails/pages/ManytoMany...
tisp (Guest)
on 2007-01-19 17:31
(Received via mailing list)
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
This topic is locked and can not be replied to.