ActiveRecord has two associations

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"#, :foreign_key => ""
end

class Game < ActiveRecord::Base
  belongs_to :team, :class_name => "Team" #, :foreign_key => "team_id"
  belongs_to :opponent, :class_name => "Team" #, :foreign_key => "opponent_id"
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 # return all games home or away
@game.hosting_team # Team
@game.opposing_team # Team
+5
source share
1 answer

Perhaps you are still modeling it using the bt / ho associations and set up the games as a team access method rather than an association:

class Team < ActiveRecord::Base
  def games
    Game.find(:conditions => ["home_team_id = ? OR away_team_id = ?", id, id])
  end
end
+3
source

All Articles