I have a Teams model and a Fixtures model. The Fixtures model has an away team and a home team.I followed the example in this answer and have most things working.
I think the best way would be to write an instance method for that:
In the Team model:
def games
Fixture.where("home_id = ? OR away_id = ?", self.id, self.id)
end
Use it like a regular method:
Team.first.games
#=> [<Fixture id: ... >, <Fixture id: ... >, ... ]
This should return an ActiveRecord::Relation which is re-usable for scope-chaining, etc.
(Here is a similar question, but with has_one
: Rails Model has_many with multiple foreign_keys)
Also, you could make a class method from it using the id of the Team (if you already have the team_id but not the Team instance object):
class Team < ActiveRecord::Base
has_many :home_games, :class_name => 'Fixture', :foreign_key => 'home_id'
has_many :away_games, :class_name => 'Fixture', :foreign_key => 'away_id'
def games
Team.games(self.id)
end
def self.games(team_id)
Fixture.where('fixtures.home_id = ? OR fixtures.away_id = ?', team_id, team_id)
end
end
And use it like this:
Team.games(params[:team_id])
# or
@team = Team.where(id: params[:id]).first
@team.games