ggn
ggn

Reputation: 25

Which type of association?

I'm trying to store teams and their matches in a database. There are several teams and several matches. Every match is played by two teams.

This is my MySQL scheme.

CREATE TABLE teams (
   id INT(11) NOT NULL auto_increment,
   name VARCHAR(255) NULL,
   PRIMARY KEY (id),
   UNIQUE KEY (name)
);

CREATE TABLE matches (
   id INT(11) NOT NULL auto_increment,
   datetime datetime NULL,
   team_home INT(11) NOT NULL,
   team_guest INT(11) NOT NULL,
   result_home INT(11) NOT NULL,
   guest_home INT(11) NOT NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (team_home) REFERENCES teams (id),
   FOREIGN KEY (team_guest) REFERENCES teams (id)
);

Now I'd like to build these schemes in Rails, but I have no idea to choose the right associations. How can I do references over two fields (in my example team_home and team_guest to teams)?

Upvotes: 1

Views: 57

Answers (1)

house9
house9

Reputation: 20614

Like @Sumit Munot said you should go through the guides, lots of good information there

as a learning exercise try using some of rails generators to see how rails likes things named

rails generate model Team name:string 
rails generate model Match start_at:datetime team_home_id:integer team_away_id:integer score_home_team:integer score_away_team:integer

then view and modify the files created in db/migrations adding null: false as needed

NOTE: I changed some of your column names slightly

once your migrations are dialed create your database tables using rake db:migrate

then modify the models that were generated in app/models and add the relationships

class Team
  has_many :home_matches, class_name: "Match", foreign_key: "team_home_id"
  has_many :away_matches, class_name: "Match", foreign_key: "team_away_id"

  def matches
    (home_matches + away_matches).flatten.sort_by(:start_at)
  end
end

class Match
  belongs_to :home_team, class_name: "Match", foreign_key: "team_home_id"
  belongs_to :away_team, class_name: "Match", foreign_key: "team_away_id"
end

Normal associations do not need to be so complex, lets say you had a Player model i.e.

rails generate model Player name:string team_id:integer

class Player
  belongs_to :team
end

class Team
  has_many :players
end

as long as the players table has a team_id column it will just 'work'

Upvotes: 1

Related Questions