# Deeply nested assocations

**URL:** <https://www.ruby-forum.com/t/deeply-nested-assocations/158475>\
**Category:** Rails\
**Created:** [January 23, 2009, 6:25pm UTC](https://www.ruby-forum.com/t/deeply-nested-assocations/158475 "2009-01-23T18:25:04Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![himdel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/c67d28/32.png) [@himdel](https://www.ruby-forum.com/u/himdel)\
**Post date:** [January 23, 2009, 6:25pm UTC](https://www.ruby-forum.com/t/deeply-nested-assocations/158475/1 "2009-01-23T18:25:04Z")

</div>

I am working on a database that has the following associations It’s  
not my database, so I am stuck with the structure):

class DimTeam \< ActiveRecord::Base  
set\_primary\_key “team\_id”  
has\_many :work\_match\_map\_teams, :foreign\_key =\> “to\_team\_id”  
end

class WorkMatchMapTeam \< ActiveRecord::Base  
set\_primary\_key “map\_id”  
belongs\_to :work\_match, :foreign\_key =\> “work\_match\_id”  
belongs\_to :dim\_team, :foreign\_key =\> “to\_team\_id”  
end

class WorkMatch \< ActiveRecord::Base  
set\_primary\_key “work\_match\_id”  
has\_many :work\_balls, :foreign\_key =\> “work\_match\_id”  
has\_many :work\_match\_map\_teams, :foreign\_key =\> “work\_match\_id”  
end

class WorkBall \< ActiveRecord::Base  
set\_primary\_key “work\_ball\_id”  
belongs\_to :work\_match, :foreign\_key =\> “work\_match\_id”  
end

I can carry out a find as follows:  
home\_team = DimTeam.find(@search.home\_team\_id, :include =\>  
[:work\_match\_map\_teams, {:work\_match\_map\_teams =\> :work\_match },  
{:work\_match\_map\_teams =\> {:work\_match =\> :work\_balls}}])  
and while this takes a while, it works.  
I’d like to be able to do something like  
home\_team.work\_match\_map\_teams.work\_match.work\_balls  
but this breaks down because home\_team.work\_match\_map\_teams is an  
array.

I’ve tried  
team1\_matches = home\_team.work\_match\_map\_teams.map {|m|  
m.work\_match} but that _is_ slow, as it makes a SQL call every time  
map is invoked and I still haven’t got the required result!

Can anybody please suggest a way in which I can achieve the above with  
an efficient SQL call?
