2014-06-05 34 views
0

一直在教自己如何构建一个简单的ruby/rails网站。现在试图找出数据处理的注意事项。小组正在工作,我如何“总结”所有列?RoR:如何使查询返回每个组的总和值?

index.html.erb

<table> 

<tr> 
<th>Site</th> 
<th><7days</th> 
<th>>7days</th> 
<th>>30days</th> 
<th>>90days</th> 
<th>>180days</th> 
<th>>365days</th> 

</tr> 
<tr> 

<% @gdcomets.each do |dcomet| %> 

<td><%= dcomet.site %></td> 
<td><%= @sum1 %></td> 
<td><%= @sum2 %></td> 
<td><%= @sum3 %></td> 
<td><%= @sum4 %></td> 
<td><%= @sum5 %></td> 
<td><%= @sum6 %></td> 

</tr> 

<% end %> 

</table> 

dcomets_controller

class DcometsController < ApplicationController 

# GET /dcomets 
# GET /dcomets.json 
def index 

@dcomets = Dcomet.all 

@gdcomets = Dcomet.group(:site) 

@sum1 = @gdcomets.map(&:ls7day).sum 
@sum2 = @gdcomets.map(&:gt7day).sum 
@sum3 = @gdcomets.map(&:gt30day).sum 
@sum4 = @gdcomets.map(&:gt90day).sum 
@sum5 = @gdcomets.map(&:gt180day).sum 
@sum6 = @gdcomets.map(&:gt365day).sum 


respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @gdcomets } 
end 
end 
end 

回答

0

你会得到更好的性能让SQL做总结的一切繁琐的工作:

Dcomet.group(:site).sum(:data) 

其中:数据是要总结列的名称。这将返回一个散列,其中键是网站值,并且该值相应的总和为该网站

+0

我该如何制作:数据为每个列的变量? – user3712834

+0

更好的问题,我该如何处理这个散列使其成为表格的一部分? – user3712834

+0

您可以遍历散列或对这些值进行求和。由你决定。查看Hash文档:http://ruby-doc.org/core-2.1.2/Hash.html。也可以在命令行上查看输出的内容。 – ReggieB

1
@sum = @gdcomets.map(&:data).sum 

:数据是要总结的列名。

+0

我补充说我的index.html或控制器? – user3712834

+1

在控制器 – Iceman

+0

我今天下午已经搞乱了很多,有些东西仍然不能正常工作。我更新了上面的两个文件。 – user3712834