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.
class Fixture < ActiveRecord::Base
belongs_to :home, class_name: 'Team'
belongs_to :away, class_name: 'Team'
end
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'
end
I want to be able to call @team.fixtures to get a list of all of the teams fixtures, currently @team.home_games gives me the home fixtures and @team.away_games gives me the aways.
How can I write a has_many :games
similar to has_many :home_games
, and is that the best way to do it?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With