2012-05-30 28 views
4

所以我試圖對模型偉大的granchildren執行查詢。的關係是如此...Rails 3檢索所有偉大的孫子記錄作爲ActiveRecord收集

錦標賽>比賽>比賽>玩家

和比賽模式:

class Tournament < ActiveRecord::Base 
    has_many :competitions, :dependent => :destroy 
    has_many :matches, :through => :competitions 
    has_many :players, :through => :matches 

end 

目前我有什麼檢索所有偉大的曾孫記錄是:

@results = @tournament.competitions.collect{|b| b.matches.collect{|c| c.players.with_win_count}}.flatten 

而這個工作,但問題是,它返回一個數組。我想要做的是建立一個基於用戶輸入的動態查詢,而玩家表本質上是所有匹配的結果池,用戶可以選擇只過濾他想看到的內容。我最終得到的是一個相當複雜的(取決於用戶輸入)查詢,並且附加的where子句不能在數組上執行。爲了給你這是怎麼打算的工作更好的主意,這裏是我的代碼...

def results 
    @tournament = Tournament.find(params[:id]) 
    @results = @tournament.all_great_grandchildren 
    @results.where(params[:player_condition1]) if params[:player_condition1] 
    @results.where(params[:player_condition2]) if params[:player_condition2] 
    @results.where(params[:player_condition3]) if params[:player_condition3] 

    if params[:match_condition] 
    #Join to match table so we can query the match fields 
    @results.join(:match) 
    @results.where(params[:match_condition]) 
    end 
    .... 
    @results.order(params[:order]) if params[:order] 
end 

有沒有辦法找到所有對於任何給定賽事曾孫(播放器)記錄的無陣列所以我可以繼續調節記錄?

回答

8

我認爲你應該打電話@tournament.players將開箱即用,如果你已經設置了上述關聯。

+0

爾加,它是如此簡單!難怪我沒有找到....事後看來,我意識到我也可以簡單地完成'@results = Player.join(:match =>:competition)@results = @ results.where(「competition.tournament_id = ?「,@ tournament.id)',但你的方法看起來更乾淨。 – Noz

+0

不客氣。 :) – Chamnap

1

Chamnap已經得到它。我們在模型中定義「has_many」和「belongs_to」關聯的原因是讓我們可以輕鬆訪問關聯模型。

所以,當你有一個名爲錦標賽錦標賽對象,你可以做

competitions = tournament.competitions 
matches = tournament.matches 
players = tounaments.players 

您也可以在相反方向上,從一個球員的對象。例如:matches = player.matches

使用Active Record時,您在處理關聯時不必進行手動連接或原始SQL模型調用。有Actice紀錄協會指導的快速閱讀:

http://guides.rubyonrails.org/association_basics.html