# Getting many to many polymorphic associations to work as advertised

**URL:** <https://www.ruby-forum.com/t/getting-many-to-many-polymorphic-associations-to-work-as-advertised/184672>\
**Category:** Rails\
**Created:** [March 6, 2010, 11:42am UTC](https://www.ruby-forum.com/t/getting-many-to-many-polymorphic-associations-to-work-as-advertised/184672 "2010-03-06T11:42:50Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tribalvibes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/34f0e0/32.png) [@tribalvibes](https://www.ruby-forum.com/u/tribalvibes)\
**Post date:** [March 6, 2010, 11:42am UTC](https://www.ruby-forum.com/t/getting-many-to-many-polymorphic-associations-to-work-as-advertised/184672/1 "2010-03-06T11:42:50Z")

</div>

Could anyone please help? Getting exceptions trying to implement:

module P  
class List \< ActiveRecord::Base  
has\_many :list\_items  
has\_many :items, :through =\> :list\_items

has\_many :contacts, :source =\> :item, :through =\> :list\_items,  
:source\_type =\> “P::Contact”

has\_many :users, :source =\> :item, :through =\> :list\_items,  
:source\_type =\> “P::User”  
end

class ListItem \< ActiveRecord::Base  
belongs\_to :list  
belongs\_to :item, :polymorphic =\> true  
end

class Contact \< ActiveRecord::Base  
has\_many :lists, :through =\> :list\_items  
has\_many :items, :as =\> :item  
end

class User \< ActiveRecord::Base; end # associations like Contact

end

Trying to make List of ListItem where the item is any of Contact,  
User, etc.

Several problems:

1. P::List.find(:first).contacts does not narrow by the item\_type and  
instead returns e.g. Contacts with ids from User items. Adding  
:conditions =\> ‘item\_type = “P::Contact”’  
to the :has\_many :contacts fixes this but,

2. P::List.find(:first).items (which should return all items of all  
item\_types in the first list) instead throws:

ActiveRecord::HasManyThroughAssociationPolymorphicError: Cannot have a  
has\_many :through association ‘P::List#items’ on the polymorphic  
object ‘Item#item’.

I’ve been scratching on this for a while now. Could someone please  
explain wtf is going on with this setup ?

Thanks,  
tv
