2016-03-19 36 views
0

我敢肯定,這對大部分人來說都是公然的簡單,但作爲一個noob,我有一個問題,它圍繞着我的大腦。Ruby on Rails:使用數組結果的查詢

我有一個叫季模型,其中的數據是這樣的 - (所有字段名的全部小寫,與帽可讀性如下圖所示)

Record Sport  SeasonNumber 
    1  Football 84 
    2  Baseball 76 
    3  Basketball 52 
    4  Hockey  26 
    5  Football 85 
    6  Baseball 77 
    7  Basketball 53 
    8  Hockey  27 

的,因爲增加了數據的方式,我知道Sport專欄的順序總是相同的。

我有另外一個模型中,我們會打電話給教練,看起來像這樣(只,我要問一下相關字段顯示以表簡明。)

Record Sport  Season CoachName + otherdata 
    1 Football  84 Joe Smith 
    2 Football  84 Bob Jones 
    3 Football  84 Alex Trebek 
    4 Football  84 Computer 
    5 Football  84 Computer 
    6 Football  84 Computer 
    7 Baseball  76 Hank Aaron 
    8 Baseball  76 Computer 
    9 Football  85 Joe Smith 
    10 Football  85 Bob Jones 
    11 Football  85 Computer 
    12 Football  85 Computer 
    13 Football  85 Computer 
    14 Football  85 Sam Spade 
    ... etc. 

我所想要做的是,對於Sport/SeasonNumber [四項運動,只有每個賽季的最新賽季]最近的「組合」,請計算非「計算機」的教練名稱數量。

所以首先我拉過去的4條從本賽季表

@seasons = Season.last(4) 

現在我想通過@seasons陣列來迭代在最新一季的每個運動讓人類教練的計數。如果我只有過一個 「套」 的數據(例如 「足球,87」,我可以這樣做:

控制器

[email protected] 
[email protected] 
humancount=Coach.human(sp,sn) 

型號

scope :people, -> {where.not(coachname: "Computer")} 

def self.human(sp,sn) 
humans=Coach.people.count.where(["sport = ? and season = ?", sp,sn]) 
end 

但是,我想要什麼迴歸是一個數組,它是「足球人類」,「棒球人類」,「籃球人類」和「曲棍球人類」的統計數字。我如何將結果/元素@seasons傳遞給方法並得到數組作爲回報?我試圖避免寫一個針對足球的查詢,一個針對棒球,一個針對籃球,另一個針對籃球年。

認爲答案在於使用.map但我只是不適合它。或者,也許我只需要遍歷@seasons數組中的每個「記錄」?

回答

0
num_human_football_coaches = Coach.where("name != ?", "Computer").where(sport: "Football").count 
0

你應該做這樣的

Coach.where("name != ?", "Computer").group(:sport).count 

你想要的東西這回你。

+0

關閉,但這將返回所有季節特定運動的計數。我只想爲特定的賽季計數,但我可能不清楚這個問題。 –

0

我最終只是通過「蠻力」來做到這一點。

[email protected] 
footballhumancount=Coach.human("football",sn) 
baseballhumancount=Coach.human("baseball",sn) 
basketballhumancount=Coach.human("basketball",sn)