Belongs_to too many columns ID
I'm trying to create a Matches table. This matches table will look to get it's information from a Teams table. I'm having trouble getting the association to work.
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
My Match table has
# id
# hometeam_id
# awayteam_id
# …
My Team table has
# id
# name
# …
I want to be able to do the following
game = Match.find(:first)
# <Match id: 1, hometeam_id: 64810937, awayteam_id: 78380562,
game.hometeam
# returns "Toronto"
I'm not too sure if my belongs_to is the right way to do it. I feel like I'm repeating myself and their might开发者_如何学C be a better approach. Thoughts?
UPDATE SOLVED
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
Leaving this up for anyone else who runs into similar problems.
Try this:
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
精彩评论