2013-07-04 77 views
7

我有一个团队模型和Fixtures模型。 Fixtures模型有一个客队和一个主队。我遵循this answer的例子,并且有大部分的工作。Rails has_many自定义ActiveRecord协会

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 

我希望能够调用@ team.fixtures得到所有车队灯具的名单,目前@ team.home_games给我的家庭灯具和@ team.away_games给我的跳投。 我该怎么写has_many :games类似于has_many :home_games,这是做到这一点的最好方法吗?

回答

7

我认为最好的办法是写为实例方法

在组队模式:

def games 
    Fixture.where("home_id = ? OR away_id = ?", self.id, self.id) 
end 

使用它像一个普通的方法:

Team.first.games 
#=> [<Fixture id: ... >, <Fixture id: ... >, ... ] 

这应该返回一个ActiveRecord :: Relation其中重新使用乐为作用域链

(这里有一个类似的问题,但has_oneRails Model has_many with multiple foreign_keys


此外,您可以使用团队的ID从它使一个类的方法(如果你已经有了TEAM_ID而不是团队的实例对象):

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 

而且使用这样的:

Team.games(params[:team_id]) 
# or 
@team = Team.where(id: params[:id]).first 
@team.games 
+0

看起来不错,谢谢! –