Cydonia7
Cydonia7

Reputation: 3826

Rails match model

I've got a Match and a Team model in my Rails application.

A match has two teams team1 and team2. How do I set up my Team model to make it have an attribute matches containing matches when the team is team1 and when the team is team2 ?

Note: I'd like to be able to use it like any Rails association like matches.delete_all for instance.

Upvotes: 0

Views: 497

Answers (2)

rome3ro
rome3ro

Reputation: 129

the problem with this approach is that you are not going to be able to access to the team through the match, for example "match.home_team"

Upvotes: 0

tee
tee

Reputation: 4409

There are two associations. I used home_team and away_team instead of team1 and team2:

class Match
  belongs_to :home_team, :class => 'Team', :foreign_key => 'home_team_id'
  belongs_to :away_team, :class => 'Team', :foreign_key => 'away_team_id'

class Team
  has_many :home_matches, :class_name => 'Match', :foreign_key => 'home_team_id'
  has_many :away_matches, :class_name => 'Match', :foreign_key => 'away_team_id'

To delete all matches for a team, you need to delete both associated matches. In team.rb:

def delete_all_matches
  home_matches.delete_all
  away_matches.delete_all
end

Upvotes: 1

Related Questions