I think the best way is to write an instance method for this:
In the Team model:
def games Fixture.where("home_id = ? OR away_id = ?", self.id, self.id) end
Use it as a regular method:
Team.first.games #=> [<Fixture id: ... >, <Fixture id: ... >, ... ]
This should return ActiveRecord :: Relation , which is reused for binding to scope , etc.
(Here is a similar question, but with has_one : Rails Model has_many with several foreign_keys )
In addition, you can make a class method from it using the team identifier (if you already have team_id, but not an object of the Team instance):
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 as follows:
Team.games(params[:team_id])
MrYoshiji Jul 04 '13 at 18:51 2013-07-04 18:51
source share