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

**URL:** <https://www.ruby-forum.com/t/two-side-polymorphic-association-or-how-to-link-multiple/81689>\
**Category:** Rails\
**Created:** [January 11, 2007, 12:52pm UTC](https://www.ruby-forum.com/t/two-side-polymorphic-association-or-how-to-link-multiple/81689 "2007-01-11T12:52:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![tisp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/9fc348/32.png) [@tisp](https://www.ruby-forum.com/u/tisp)\
**Post date:** [January 11, 2007, 12:52pm UTC](https://www.ruby-forum.com/t/two-side-polymorphic-association-or-how-to-link-multiple/81689/1 "2007-01-11T12:52:13Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![tisp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/9fc348/32.png) [@tisp](https://www.ruby-forum.com/u/tisp)\
**Post date:** [January 19, 2007, 4:31pm UTC](https://www.ruby-forum.com/t/two-side-polymorphic-association-or-how-to-link-multiple/81689/2 "2007-01-19T16:31:16Z")

</div>

i think this might be what you are looking for:

[http://wiki.rubyonrails.org/rails/pages/ManytoManyPolymorphicAssociations](http://wiki.rubyonrails.org/rails/pages/ManytoManyPolymorphicAssociations)

---

<div class="post-metadata">

**Author:** ![tisp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/9fc348/32.png) [@tisp](https://www.ruby-forum.com/u/tisp)\
**Post date:** [January 19, 2007, 4:31pm UTC](https://www.ruby-forum.com/t/two-side-polymorphic-association-or-how-to-link-multiple/81689/3 "2007-01-19T16:31:41Z")

</div>

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
