I’m working on a Rails-based web service that provides data about various sports team schedules. I have models that included the following:
- Each Game record has a “home” and an “away” team, each of which references a Team record
- Each Team record belongs to a Division record
I have modeled Game as follows:
class Game < ActiveRecord::Base
# Miscellaneous validations here
belongs_to :home_team, :class_name => Team
belongs_to :away_team, :class_name => Team
# Other stuff follows
end
Here is the model for Team:
class Team < ActiveRecord::Base
# Miscellaneous validations here
belongs_to :division
# Other stuff follows
end
And here is the model for Division:
class Division < ActiveRecord::Base
# Miscellaneous validations here
has_many :teams, :dependent => :destroy
# Other stuff follows
end
I am trying to implement a request to return all games where the home team and the away team are both from a specific division. In pseudo-code , I want something like:
SELECT games.* FROM games WHERE
"The division ID of the home team" = '1' AND
"The division ID of the away team" = '1'
I’ve tried various incarnation using the joins method, none of which have worked for me. The closest I’ve come is this:
games = Game.joins(:home_team, :away_team).where(
:home_team => {:division_id => params[:division_id]},
:away_team => {:division_id => params[:division_id]})
but this gives me an error:
SQLite3::SQLException: no such column: home_team.division_id: SELECT "games".* FROM "games" INNER JOIN "teams" ON "teams"."id" = "games"."home_team_id" INNER JOIN "teams" "away_teams_games" ON "away_teams_games"."id" = "games"."away_team_id" WHERE "home_team"."division_id" = '1' AND "away_team"."division_id" = '1'
Clearly, my syntax for specific home_team and away_team isn’t working because it’s not mapping them to a valid table name of “teams”. But any other variant of the join I come up with seems to get me even further from what I want.
I’d appreciate any help you can provide or references to documentation that shows me how to do this kind of thing.
I think you might be able to try something like this:
You have the nested query, which is a little annoying, but it lets you avoid having to join twice against the teams table.