# Association problem in one direction

**URL:** <https://www.ruby-forum.com/t/association-problem-in-one-direction/130262>\
**Category:** Rails\
**Created:** [February 26, 2008, 9:13pm UTC](https://www.ruby-forum.com/t/association-problem-in-one-direction/130262 "2008-02-26T21:13:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [February 26, 2008, 9:13pm UTC](https://www.ruby-forum.com/t/association-problem-in-one-direction/130262/1 "2008-02-26T21:13:41Z")

</div>

I have these models

class Game \< ActiveRecord::Base  
belongs\_to :home\_team, :class\_name =\> ‘Team’  
belongs\_to :away\_team, :class\_name =\> ‘Team’  
belongs\_to :field  
end  
class Person \< ActiveRecord::Base  
has\_many :affiliations  
has\_many :teams, :through =\> :affiliations  
end  
class Team \< ActiveRecord::Base  
has\_many :affiliations  
has\_many :players, :through =\> :affiliations, :source =\> :person  
has\_many :games  
end  
class Affiliation \< ActiveRecord::Base  
belongs\_to :person  
belongs\_to :team  
end

I with the associations above, I can get the players for the teams,  
the home team and away team players from the games.

I want to be able to go back and get the games that each team and/or  
player plays in. The associations work in one direction but not in the  
other. How do I work back through the home\_team and away\_team  
connections and get home games, away games and the totals for a given  
player or team?

Any ideas?

Thanks

Andrew

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [February 27, 2008, 12:31pm UTC](https://www.ruby-forum.com/t/association-problem-in-one-direction/130262/2 "2008-02-27T12:31:51Z")

</div>

Rails cannot infer how to get from Games → Teams, from your models  
rails is looking for team\_id in Games

Based on your models, I can see only one way:

class Team \< ActiveRecord::Base  
has\_many :affiliations  
has\_many :players, :through =\> :affiliations, :source  
=\> :person  
has\_many :home\_games, :class =\> ‘Games’, :foreign\_key =\>  
‘home\_team\_id’  
has\_many :away\_games, :class =\> ‘Games’, :foreign\_key =\>  
‘away\_team\_id’  
end

You could then access team.away\_games and team.home\_games

On Feb 26, 3:13 pm, “removed\_email\_address@domain.invalid” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
