【问题标题】:Multi Model Associations多模型关联
【发布时间】:2015-05-05 14:30:42
【问题描述】:

我正在构建一个类似网络应用程序的体育联盟。有3个模型,都相互关联。玩家(用户)、团队和游戏。球队有很多球员,也有很多比赛。玩家有很多游戏,并且可以有多个团队。游戏属于球队和球员。

Teams: have_many :players
Teams: have_many :games

Players: have_many :teams
Players: have_many :games

Games: belong_to :teams
Games: belong_to :players

有没有办法使用“has_many through”表创建“三重关联”?我倾向于“has_many through”,然后在“through”表中跟踪每个玩家的响应状态。我还希望两支球队都在“通过”表中,这样我就可以做类似 (player_id, team_id, game_id) 的事情,并且只为两支球队创建一场比赛。

或者我上面的工作有效吗?还是我完全不在乎我的想法,走错路了?

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    你可以试试这个:

       class Game < ActiveRecord::Base
          belongs_to :gameable, polymorphic: true
        end
    
        class Team < ActiveRecord::Base
          has_many :games, as: :gameable
          has_many :players, through: :matches
        end
    
        class Player < ActiveRecord::Base
          has_many :games, as: :gameable
          has_many :teams, through: :matches
        end
    
        class Match < ActiveRecord::Base
          belongs_to :players
          belongs_to :teams
        end
    

    希望这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多