Rails has_many custom ActiveRecord Association

I have a command model and a Fixtures model. The Fixtures model has a guest team and a home team. I followed the example of this answer and worked on most.

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 the teams, currently @ team.home_games gives me home lights and @ team.away_games gives me aways. How to write has_many :games similar to has_many :home_games and is this the best way to do this?

+7
database ruby-on-rails activerecord
Jul 04 '13 at 18:42 on
source share
1 answer

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]) # or @team = Team.where(id: params[:id]).first @team.games 
+7
Jul 04 '13 at 18:51
source share



All Articles