当前位置:  开发笔记 > 编程语言 > 正文

如何从下游对象的子集中获取复杂活动记录has_many的列表

如何解决《如何从下游对象的子集中获取复杂活动记录has_many的列表》经验,为你挑选了0个好方法。

当在中间的关系上实现多个外键时,我很难从分层父关系中获取所涉及的游戏列表.

鉴于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和组合数据.

推荐阅读
云聪京初瑞子_617
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有