2013-07-04 20 views
7

Mam model Teams i model Fixtures. Model Fixtures ma drużynę gości i drużynę gospodarzy. Podążyłem za przykładem w this answer i większość rzeczy działa.Szyny has_many niestandardowe ActiveRecord Association

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 

chcę móc wywoływać @ team.fixtures aby uzyskać listę wszystkich zespołów lamp, obecnie @ team.home_games daje mi opraw domu i @ team.away_games daje mi wynos. Jak mogę napisać has_many :games podobną do has_many :home_games i czy to najlepszy sposób na zrobienie tego?

Odpowiedz

7

Myślę, że najlepszym sposobem byłoby napisać metodę instancji na to:

w modelu zespołu:

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

używać go jak zwykły sposób:

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

To powinno zwrócić ActiveRecord :: Relation, który jest re-usab le na zakres-łańcuchowym itp

(Oto podobne pytanie, ale z has_one: Rails Model has_many with multiple foreign_keys)


Również można zrobić metody klasy z niego przy użyciu identyfikatora Zespołu (jeśli masz już team_id ale nie instancja obiektu Team):

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 

i używać go tak:

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

wygląda dobrze, dzięki! –

Powiązane problemy