Question

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.

No correct solution

OTHER TIPS

In this situation, you'd use @team.id for each, like @EricAndres said.

However, you'll also want some additional parenthesis in your where clause to make it work right:

@team.games.where("(home_team_id = ? AND home_score > away_score) OR (away_team_id = ? AND away_score > home_score)", @team.id, @team.id)

Update

Since this is on the Game model, how about a class method on that model called won_by which takes a team:

class Game < ActiveRecord::Base

  def self.won_by(team)
    where("(home_team_id = ? AND home_score > away_score) OR (away_team_id = ? AND away_score > home_score)", team.id, team.id)
  end

end

You need to use @team.id for each.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top