2012-08-07 62 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