# Polymorphic many-to-many relationship?

**URL:** <https://www.ruby-forum.com/t/polymorphic-many-to-many-relationship/175022>\
**Category:** Rails\
**Created:** [September 6, 2009, 9:43am UTC](https://www.ruby-forum.com/t/polymorphic-many-to-many-relationship/175022 "2009-09-06T09:43:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cojones](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/9f8e36/32.png) [@cojones](https://www.ruby-forum.com/u/cojones)\
**Post date:** [September 6, 2009, 9:43am UTC](https://www.ruby-forum.com/t/polymorphic-many-to-many-relationship/175022/1 "2009-09-06T09:43:36Z")

</div>

Good morning,

I need to implement a many-to-many polymorphic relationship. Any of my  
books, Google and the search couldn’t help me.

habtm doesn’t work cause it doesn’t support :polymorphic so this is my  
approach so far:

ActivityType model:  
has\_many :activity\_type\_scopes, :as =\> :resource

BuildingType model:  
has\_many :activity\_type\_scopes, :as =\> :activity\_type\_id  
BlockType model:  
has\_many :activity\_type\_scopes, :as =\> :activity\_type\_id

ActivityTypeScope model:  
belongs\_to :activity\_type  
belongs\_to :resource, :polymorphic =\> true

ActivityTypeScope migration:  
create\_table :activity\_type\_scopes, :id =\> false do |t|  
t.integer :activity\_type\_id  
t.integer :resource\_id  
t.string :resource\_type  
t.timestamps  
end

I don’t really like that approach but 2.2.2 doesn’t seem to have a  
decent solution to this. Anyway when I load a the fuxture  
ActivityTypeScope:  
one:  
activity\_type: burglary  
resource: \<%= BuildingType.find(Fixtures.identify(:row\_house)) %\>

It says BuildingType with the ID 1234567 couldn’t be found, if I use the  
ID instead of BuildingType.find(Fixtures.identify(:row\_house)) I get no  
errors but resource\_id and resource\_type is NULL in the database.

Anyone knows what’s wrong with this or - even better - does anyone have  
a better solution to my polymorphic habtm problem?

Thanks a lot,  
Heinz

---

<div class="post-metadata">

**Author:** ![cojones](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/9f8e36/32.png) [@cojones](https://www.ruby-forum.com/u/cojones)\
**Post date:** [September 6, 2009, 10:47am UTC](https://www.ruby-forum.com/t/polymorphic-many-to-many-relationship/175022/2 "2009-09-06T10:47:51Z")

</div>

Managed to get it working by changing the fixture to:  
resource: \<%= Fixtures.identify(:row\_house) %\>  
resource\_type: BuildingType

Still don’t like it cause that’s not what RoR is about. Any help would  
be still highly appreciated 🙂
