Rails has_many似乎不起作用

时间:2013-04-07 17:22:41

标签: ruby-on-rails has-many-through

我需要第二眼。当我在两个玩家之间创建一个匹配时,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

1 个答案:

答案 0 :(得分:1)

您需要有一个双:through关系:

player_matchesmatchesplayersplayer_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