Rails has_many通过似乎不工作

问题描述:

我需要第二套眼睛在这个。当我在两个玩家之间创建一个Match时,Tournament.players会返回一个空数组。Rails has_many通过似乎不工作

代码

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 
+0

你可以添加你的'Match'模型吗? – Zippie 2013-04-07 17:26:00

+0

雅,我们需要看到'Match'模型 – OneChillDude 2013-04-07 17:40:06

+0

考虑到'Tournaments'和'Player''有很多玩家匹配,你也可以考虑多态性 – OneChillDude 2013-04-07 17:42:23

你需要有一个双重:through关系:通过player_matches

player_matches通过matchesplayers

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