2012-08-07 66 views
0

我在RoR的初學者,我用具有6000行數據的數據庫玩弄左右。由於開頭的數據太多,因此我通過在控制器/索引視圖中使用這個索引表,只顯示具有唯一項目名稱的數據行。回報率 - 計算唯一值

@glyphs_test = Glyph.group(:item) 

除了每一行,我想顯示特定項目在整個數據庫中出現的次數。 當我嘗試這個,它的工作原理,但我不知道如何打印出索引。

Glyph.group(:item).uniq.count 

結果與,例如:

=> {"Eternal Fire" => 8, "Glyph of Adrenaline Rush" => 74} etc... 

就算我是能夠打印出只有在這個數,我怎麼能與之匹敵了表?我想我在這裏錯過了一些關鍵的東西。我可以通過在show#控制器中使用此功能,而不是在index#控制器中在單個記錄中執行此操作。

@glyph = Glyph.find(params[:id]) 
@glyphs = Glyph.where(["item = ?", @glyph.item]).order('net_gain ASC') 

預先感謝您的任何建議。也許我應該做更簡單的事情,但必須有解決方案。

回答

0

你可以通過你的結果散列的東西,如迭代以下

@glyph_counts = Glyph.group(:item).uniq.count 

@glyph_counts.each do |key, value| 
    #key is the item, value is the count, using key and value as the object is a hash 
    # do your printing here 
end 

或者,如果你迭代通過你的字形,並試圖得到的結果數,你可以做以下

@glyphs = Glyph.all 
@glyph_counts = Glyph.group(:item).uniq.count 

@glyph.each do |glyph| 
    #something with your glyph 
    count = @glyph_counts[@glyph.item] 
end 
+0

這樣做!謝謝! – user1582261 2012-08-07 15:24:09