【发布时间】:2017-06-09 12:33:47
【问题描述】:
当在中间的关系上实现多个外键时,我很难从分层父关系中获取所涉及的游戏列表。
给定联赛对象NFC,找到它的所有游戏对象[G1,G3,G4]
# id :integer not null, primary key
# name :string
class League
has_many :teams
# has_many :games, :through => :teams (Is there some way to do this?)
end
# id :integer not null, primary key
# team_name :string
# league_id :integer
class Team
belongs_to :league
has_many :home_games, :foreign_key => team_a_id, :source => :game
has_many :away_games, :foreign_key => team_b_id, :source => :game
end
# id :integer not null, primary key
# game_name :string
# team_a_id :integer not null
# team_b_id :integer not null
class Game
belongs_to :home_team, :class_name => Team
belongs_to :away_team, :class_name => Team
end
数据示例:
LEAGUE - TEAM - GAME
---------------------------------
AFC -
PATRIOTS -
Home Away
G1(PATRIOTS vs DALLAS)
G2(PATRIOTS vs PITTSBURG)
PITTSBURG -
G2(PATRIOTS vs PITTSBURG)
NFC -
DALLAS -
G1(PATRIOTS vs DALLAS)
G3(DALLAS vs GREENBAY)
G4(DALLAS vs SEATTLE)
GREENBAY
G3(DALLAS vs GREENBAY)
SEATTLE
G4(DALLAS vs SEATTLE)
答案将包含符合 Rails 4 的答案。如果 Rails 4 替代方案非常低效,则可能会特别考虑 RAILS 5 答案。
nfc = League.where(name: 'NFC').first
# <answer>
puts nfc.games
## array containing objects [G1,G2,G3]
我面临的挑战是home_team / away_team 并结合来自外键的数据。
【问题讨论】:
-
我强烈建议您澄清您的问题。您似乎问了两个不同的问题:如何“从部分游戏中获取涉及的联赛列表”以及如何“查找所有拥有 NFC 球队的游戏”。您没有解释什么标准使团队成为“NFC”,而是展示了一个查询名为“NFC”的联赛的示例。
-
希望它得到澄清。
-
在单个关联中列出一个团队的比赛会简单得多,然后将
home指示为布尔值。即:Teamhas_many :games-- 主场比赛是games.where(home: true) -
@meagar 他没有将“游戏”定义为团队关系,因此无法按原样工作。
-
@coreyward 你是对的,我的错。我在关闭之前移除了赏金,我无法恢复它,但我会提供我自己的赏金。
标签: ruby-on-rails ruby-on-rails-4 activerecord has-many-through