# Nested has\_many :through

**URL:** <https://www.ruby-forum.com/t/nested-has-many-through/173264>\
**Category:** Rails\
**Created:** [August 5, 2009, 10:30pm UTC](https://www.ruby-forum.com/t/nested-has-many-through/173264 "2009-08-05T22:30:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Addy\_Naik](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecb155/32.png) [@Addy\_Naik](https://www.ruby-forum.com/u/Addy_Naik)\
**Post date:** [August 5, 2009, 10:30pm UTC](https://www.ruby-forum.com/t/nested-has-many-through/173264/1 "2009-08-05T22:30:15Z")

</div>

here is the situation

class Entity \< ActiveRecord::Base  
belongs\_to :parent, :foreign\_key =\> :parent\_id, :class\_name =\>  
‘Entity’  
end

class Player \< Entity  
end

class Team \< Entity  
has\_many :players, :foreign\_key =\> :parent\_id, :class\_name =\>  
‘Player’  
end

class Club \< Entity  
has\_many :teams, :foreign\_key =\> :parent\_id, :class\_name =\> ‘Team’  
has\_many :players, :through =\> :teams, :foreign\_key  
=\> :parent\_id, :class\_name =\> ‘Player’  
end

Mysql::Error: Not unique table/alias: ‘entities’: SELECT count(\*) AS  
count\_all FROM `entities` INNER JOIN `entities` ON  
`entities`.parent\_id = `entities`.id WHERE ((`entities`.parent\_id =  
48) AND (( (`entities`.`entity_type` = ‘Team’ ) ))) AND  
( `entities`.`entity_type` = ‘Player’ )

how do get over this problem?

---

<div class="post-metadata">

**Author:** ![Addy\_Naik](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecb155/32.png) [@Addy\_Naik](https://www.ruby-forum.com/u/Addy_Naik)\
**Post date:** [August 6, 2009, 1:35am UTC](https://www.ruby-forum.com/t/nested-has-many-through/173264/2 "2009-08-06T01:35:47Z")

</div>

Do you really need the Entity class? What else does it do for you?  
I’d just have: Club has many Teams and Team has many Players.

STI is often not worth the pain it gives.  
You could also look into ‘acts as tree’ as a solution.

---

<div class="post-metadata">

**Author:** ![Addy\_Naik](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ecb155/32.png) [@Addy\_Naik](https://www.ruby-forum.com/u/Addy_Naik)\
**Post date:** [August 6, 2009, 7:47pm UTC](https://www.ruby-forum.com/t/nested-has-many-through/173264/3 "2009-08-06T19:47:30Z")

</div>

Hmmm… this is supposed to work - the join table should have its name  
aliased. This would be a good thing to add to the Rails Lighthouse -  
[rails.lighthouseapp.com](http://rails.lighthouseapp.com)

–Matt J.
