0

我是 RoR 的初学者,我正在玩弄一个包含 6000 行数据的数据库。由于要开始的数据太多,因此通过在控制器/索引视图中使用它,我使索引表仅显示具有唯一项目名称的数据行。

@glyphs_test = Glyph.group(:item)

除了每一行,我想显示特定项目在整个数据库中出现的次数。当我尝试这个时,它可以工作,但我不知道如何将它打印到索引上。

Glyph.group(:item).uniq.count

结果,例如:

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

即使我只能打印出这个数字,我如何才能将它与表格匹配?我想我在这里遗漏了一些重要的东西。我可以通过在 show#controller 但不是在 index#controller 中使用它来在单个记录中执行此操作。

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

提前感谢您的任何建议。也许我应该做一些更简单的事情,但必须有一个解决方案。

4

1 回答 1

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
于 2012-08-07T15:10:11.920 回答