What is the best way to achieve two relationships with activerecord?
I have Team and Game models. Each team will have several games @team.games. The game will have two teams @game.hosting_teamand @game.opposing_team.
I started with two associations belongs_to/has_one, but then @team.gameswould return my home games.
Another option I can think of is to use HABTM and use a validator to ensure that only records are present. The only thing that is missing is to monitor the progress of the team. I think I need to have a lot of associations, but I'm not quite sure ...
Thank you for your help.
This is an example of what two has_many associations look like. The problem here is that I would have to call team.gamesand team.opponentsto get a complete list of my games
class Team < ActiveRecord::Base
has_many :games
has_many :opponents, :class_name => "Team"
end
class Game < ActiveRecord::Base
belongs_to :team, :class_name => "Team"
belongs_to :opponent, :class_name => "Team"
end
I would like something like this, but this is obviously not how own_to works.
class Team < ActiveRecord::Base
has_many :games
end
class Game < ActiveRecord::Base
belongs_to :hosting_team
belongs_to :opposing_team
end
My desired api will look like this.
@team.games
@game.hosting_team
@game.opposing_team
source
share