flyte321
flyte321

Reputation: 420

One Model association with two models

I have a model 'Match' that belongs to a modell called 'Team'. The Team has many matches. It looks like this:

 $class Match < ActiveRecord::Base
 belongs_to :home_team, :class_name => "Team"
 belongs_to :away_team, :class_name => "Team"

 class Team < ActiveRecord::Base
 has_many :matches

In the database i have set up properly the two needed fields home_team_id and away_team_id in the 'matches'-table. I have tried a multiple ways but whenever I do something like this in my match-controller:

 @matches = Match.find(:all, :include => :team)
 # Or:
 @matches = Match.where('team.gender = ?', true)

I get this error:

Association named 'team' was not found; perhaps you misspelled it?

It seems to me the association does not work. Any ideas?

Upvotes: 1

Views: 185

Answers (1)

Amar
Amar

Reputation: 6942

You haven't added any team association you have added home_team and away_team so include home team and away team in your code.or create team association

One more thing how will you know which one is home team and away team there should be one foreign key needed for home team or and away team and add foreign_key in your code to identify them.

Upvotes: 1

Related Questions