0

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.

you786
  • 3,659
  • 5
  • 48
  • 74
  • What's the signature of the method you're trying to write? Are you trying to get all games that were won by a given team? If so, that makes most sense as an instance method rather than a class method. – Eric Andres Nov 21 '13 at 21:02

2 Answers2

1

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
CDub
  • 13,146
  • 4
  • 51
  • 68
  • I don't have access to @team to use in this method, as it's a class method of the Game model. – you786 Nov 21 '13 at 20:57
0

You need to use @team.id for each.

Eric Andres
  • 3,417
  • 2
  • 24
  • 40
  • I don't have access to @team to use in this method, as it's a class method of the Game model. – you786 Nov 21 '13 at 20:57
  • That's not specified in the question. An edit to make that clear would be nice. – Eric Andres Nov 21 '13 at 21:00
  • Well I did mention that I'm trying to be able to write @team.games.won which I think implies that it has to be a Game model class method. But I'll edit it in anyway. – you786 Nov 21 '13 at 21:13