0

我需要对这个进行第二次观察。当我在两个玩家之间创建匹配时,Tournament.players 返回一个空数组。

代码

class Tournament < ActiveRecord::Base
  has_many :player_matches
  has_many :matches
  has_many :players, :through => :player_matches  
end

class PlayerMatch < ActiveRecord::Base
  belongs_to :player
  belongs_to :match
  belongs_to :tournament
end

class Player < ActiveRecord::Base
  has_many :player_matches
  has_many :matches, :through => :player_matches
  has_many :tournaments, :through => :player_matches
end
4

1 回答 1

2

您需要有双重:through关系:

player_matches通过matchesplayers通过player_matches

class Tournament < ActiveRecord::Base
  has_many :matches
  has_many :player_matches, :through => :matches
  has_many :players, :through => :player_matches  
end

class PlayerMatch < ActiveRecord::Base
  belongs_to :player
  belongs_to :match
end

class Player < ActiveRecord::Base
  has_many :player_matches
  has_many :matches, :through => :player_matches
  has_many :tournaments, :through => :player_matches
end

class Match < ActiveRecord::Base
  belongs_to :tournament  
  has_many :player_matches
  has_many :players, :through => :player_matches
end
于 2013-04-07T19:42:29.303 回答