Say you have a Game model which belongs_to
two Teams.
class Game < ActiveRecord::Base
belongs_to :home_team, class_name: "Team", foreign_key: "home_team_id"
belongs_to :away_team, class_name: "Team", foreign_key: "away_team_id"
end
A team can find its games by using this method of the Team class:
def games
Games.where("home_team_id = ? OR away_team_id = ?", self.id, self.id)
end
and then use @team.games.upcoming
by using this method of the Game class:
def self.upcoming
where("starts > ?", DateTime.now)
end
The scopes get merged together, and it worked perfectly.
Now I'm trying to write a method that will allow me to do this:
@team.games.won
which could be checked by
@team.games.where("home_team_id = ? AND home_score > away_score OR away_team_id = ? AND away_score > home_score", ?????, ?????)
but I can't figure out how to pass in the correct team id where the ?????'s are. Is this even possible? I have no idea what to search to find this, if it's been asked before.