我正在尝试创建一个Matches表。这个匹配表将从Teams表中获取它的信息。我无法让协会工作。
class Match < ActiveRecord::Base
#
end
class Team < ActiveRecord::Base
belongs_to :matches, :class_name => "Match", :foreign_key => "hometeam_id"
belongs_to :matches, :class_name => "Match", :foreign_key => "awayteam_id"
end
我的匹配表
# id
# hometeam_id
# awayteam_id
# …
我的团队表
# id
# name
# …
我希望能够执行以下操作
game = Match.find(:first)
# <Match id: 1, hometeam_id: 64810937, awayteam_id: 78380562,
game.hometeam
# returns "Toronto"
我不太确定我的belongs_to是否是正确的方法。我觉得我在重复自己,他们可能是一个更好的方法。想法?
更新已解决
class Match < ActiveRecord::Base
belongs_to :hometeam, :class_name => "Team"
belongs_to :awayteam, :class_name => "Team"
end
class Team < ActiveRecord::Base
has_many :homegames, :class_name => "Match", :foreign_key => "hometeam_id"
has_many :awaygames, :class_name => "Match", :foreign_key => "awayteam_id"
end
将此问题留给遇到类似问题的其他人。
答案 0 :(得分:2)
试试这个:
class Team < ActiveRecord::Base
belongs_to :hometeam, :class_name => "Match", :foreign_key => "hometeam_id"
belongs_to :awayteam, :class_name => "Match", :foreign_key => "awayteam_id"
end