当在中间的关系上实现多个外键时,我很难从分层父关系中获取所涉及的游戏列表.
鉴于League Object NFC
,找到它的所有Game对象[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
#
puts nfc.games
## array containing objects [G1,G2,G3]
我所遇到的挑战是来自外键的home_team
/ away_team
和组合数据.