Ruby on rails 与同一个表的多个外键有多个关联
我有两张桌子,Ruby on rails 与同一个表的多个外键有多个关联,ruby-on-rails,database,Ruby On Rails,Database,我有两张桌子,团队和游戏。我正在尝试设置这些表的关联,但遇到了一些问题。这是我的游戏模型及其关联: # Game Model class Game < ActiveRecord::Base belongs_to :home_team, class_name: "Team" belongs_to :away_team, class_name: "Team" belongs_to :winning_team, class_name: "Team" end 我看到它正在为游戏寻找
团队
和游戏
。我正在尝试设置这些表的关联,但遇到了一些问题。这是我的游戏
模型及其关联:
# Game Model
class Game < ActiveRecord::Base
belongs_to :home_team, class_name: "Team"
belongs_to :away_team, class_name: "Team"
belongs_to :winning_team, class_name: "Team"
end
我看到它正在为
游戏寻找团队id
,因为没有团队id
错误。但是在我的游戏
表中,我有三个外键引用同一个类。因此,我是否需要为每个主队
、客队
和获胜队
创建一个多个
class Team < ActiveRecord::Base
has_many :home_games, class_name: 'Game', foreign_key: 'home_team_id'
has_many :away_games, class_name: 'Game', foreign_key: 'away_team_id'
# This seems like a separate thing to me...
has_many :winning_games, class_name: 'Game', foreign_key: 'winning_team_id'
# Do not include winning games, since it would already be included
def games
self.home_games.to_a + self.away_games.to_a
end
end
class团队
关于数据库设计的问题不应包括ORM或应用软件。这不是数据库设计的正确工具。曾经真正的数据库设计将有三个表,游戏中有关于游戏的详细信息,团队中有关于团队的详细信息,TeamGAme作为多对多关联的连接表。@HLGEM这似乎不是关于数据库设计的问题,数据库已经以功能的方式设置好了。问题是,你能把这三种联想和一种有很多参考价值或没有参考价值的联想结合起来吗。另外,为什么建议使用联接表?在这种情况下,关于比赛的细节是两支球队的比赛,似乎一张联队表就有点过头了。也许我遗漏了什么?我认为数据库设计是正确的。@Gogocar谢谢,我开始怀疑我的方法。是的,我正在寻找一种方法,要么用一行处理一个has_____________________________________。可以肯定的是,(a)一个人拥有很多是不可能的,但是(b)就你的情况而言,你可能无论如何都不想这样。我根据模型的名称和文字背后的含义进行假设,但我会假设任何一场比赛的获胜团队都是主队或获胜团队,并且一种潜在的比赛方法会返回重复的。谢谢,这非常有效,并且让我的测试通过。非常感谢。
class Team < ActiveRecord::Base
has_many :home_games, class_name: 'Game', foreign_key: 'home_team_id'
has_many :away_games, class_name: 'Game', foreign_key: 'away_team_id'
# This seems like a separate thing to me...
has_many :winning_games, class_name: 'Game', foreign_key: 'winning_team_id'
# Do not include winning games, since it would already be included
def games
self.home_games.to_a + self.away_games.to_a
end
end