2013-07-04 75 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

看起來不錯,謝謝! –