Pregunta

I'm new to Rails and still learning the associations and I'm stuck with a model relationship. How should I associate these two models?

Model Team 
id => 1, name => Toronto
id => 2, name => Montreal
id => 3, name => Detroit

Model Game
id => 1, hometeam_id => 1, awayteam_id => 2
id => 2, hometeam_id => 3, awayteam_id => 2

class Team < ActiveRecord::Base
  ???
end

class Game< ActiveRecord::Base
  ???
end
¿Fue útil?

Solución

Something like this should work

class Team < ActiveRecord::Base
  has_many :games
end

class Game< ActiveRecord::Base
 belongs_to :hometeam, class_name: "Team", foreign_key: :hometeam_id
 belongs_to :awayteam, class_name: "Team", foreign_key: :awayteam_id
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top