哪种类型的关联?

时间:2014-04-11 21:06:26

标签: mysql ruby-on-rails

我正在尝试将团队及其比赛存储在数据库中。有几支球队和几场比赛。每场比赛都由两支球队进行。

这是我的MySQL方案。

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)
);

现在我想在Rails中构建这些方案,但我不知道选择正确的关联。如何在两个字段(在我的示例中为team_home和team_guest到团队)中进行引用?

1 个答案:

答案 0 :(得分:1)

喜欢@Sumit Munot说你应该浏览指南,那里有很多好的信息

作为一个学习练习尝试使用一些rails生成器来查看rails如何喜欢名为

的东西
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

然后查看和修改db/migrations根据需要添加null: false时创建的文件

注意:我稍微更改了一些列名

拨打您的迁移后,使用rake db:migrate

创建数据库表

然后修改在app/models中生成的模型并添加关系

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

普通关联不需要那么复杂,假设你有一个Player模型,即

rails generate model Player name:string team_id:integer

class Player
  belongs_to :team
end

class Team
  has_many :players
end

只要players表格中有team_id列,它就会工作'