我正在尝试将团队和他们的比赛存储在数据库中。有几支球队和几场比赛。每场比赛由两支球队进行。
这是我的 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 指向团队)?
最佳答案
就像@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
列,它就会“工作”
关于mysql - 哪种类型的协会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23022592/