# Polymorphic hm=\>t

**URL:** <https://www.ruby-forum.com/t/polymorphic-hm-t/161638>\
**Category:** Rails\
**Created:** [February 28, 2009, 5:31am UTC](https://www.ruby-forum.com/t/polymorphic-hm-t/161638 "2009-02-28T05:31:06Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![juli](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/dfb087/32.png) [@juli](https://www.ruby-forum.com/u/juli)\
**Post date:** [February 28, 2009, 5:31am UTC](https://www.ruby-forum.com/t/polymorphic-hm-t/161638/1 "2009-02-28T05:31:06Z")

</div>

Hi,

I have the following class architecture:

class Container \< ActiveRecord::Base  
has\_many :containments, :order =\> ‘position’  
has\_many :parent\_containments, :as =\> :containable, :class\_name =\>  
‘Containment’  
has\_many :containable\_items, :through =\> :containments, :source  
=\> :containable  
end

class Containment \< ActiveRecord::Base  
belongs\_to :container  
belongs\_to :containable, :polymorphic =\> true  
end

class ContainedThing \< ActiveRecord::Base  
has\_many :parent\_containments, :as =\> :containable, :class\_name =\>  
‘Containment’  
has\_many :containers, :through =\> :parent\_containments  
end

class OtherContainedThing \< ActiveRecord::Base  
has\_many :parent\_containments, :as =\> :containable, :class\_name =\>  
‘Containment’  
has\_many :containers, :through =\> :parent\_containments  
end

The logic is… A container can contain many items. These items may be  
being contained inside other containers as well (ie has\_and\_belongs\_to  
or has\_many :through type association). Also, it’s possible for a  
container to store other containers in itself (hence the  
parent\_containments association inside the container class).

Rails doesn’t like my code very much, though.

I can’t use the containable\_items has\_many :through association  
because Rails complains that I can’t use a polymorphic association as  
the target of a has\_many :through.

Is there something I’m missing, or do I have to do most of the work  
via hand here?

(ie no automatic methods, etc, and I have to build, destroy and  
retrieve objects with a series of lines of code rather than simple one-  
method invocations, etc.)?

Thanks heaps,  
Julian.
