2015-05-05 127 views
0

我正在构建一个像网络应用程序一样的体育联盟。有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”表中的回应状态。我也希望两队都在“直通”牌桌上,这样我就可以做类似(player_id,team_id,game_id)并且只为这两支球队创建一个游戏。

还是做了我上面的工作?还是我完全摆脱了我的摇杆,并以这种错误的方式去做?

回答

0

你可以试试这个:

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 

希望这会帮助你。