Deeply nested assocations


#1

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?