多模型关联

时间:2015-05-05 06:03:13

标签: ruby-on-rails associations

我正在建立一个像网络应用程序一样的体育联盟。共有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),并且只为两个团队创建一个游戏。

或者我上面的工作是做什么的?或者我完全偏离了摇杆并以错误的方式解决这个问题?

1 个答案:

答案 0 :(得分: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

希望这会对你有所帮助。

相关问题