2014-09-22 83 views
0

我正在编写我的第一个按日期总结数据的Rails视图。我希望每个日期都有一行,并为该日期汇总的列。按日期分小计的Rails总结

我已经能够使它工作。但是,编码很尴尬。这是我的:

<h3>Carwings Daily Summary</h3> 
<table class="display dataTable table table-striped table-bordered"  id="dataTable2"> 
    <thead> 
    <tr> 
    <th>Date</th> 
    <th># Trips</th> 
    <th>E Consumption (kWh)</th> 
    <th>E Regeneration (kWh)</th> 
    <th>E Total (kWh)</th> 
    <th>Distance (Miles)</th> 
    <th>Energy Economy (Miles/kWh)</th> 
    <th>CO2 Emission Reduction (lbs)</th> 
    </tr> 
    </thead> 
    <tbody> 
    <% trips = 0 %> 
    <% consumption = 0 %> 
    <% regen = 0 %> 
    <% total = 0 %> 
    <% distance = 0 %> 
    <% economy = 0 %> 
    <% emissions = 0 %> 
    <% sumdate = nil %> 
    <% @carwings.each.with_index do |carwing, index| %> 
     <% sumdate = carwing.date if index == 0 %> 
     <% if carwing.date == sumdate %> 
      <% trips = trips + 1 %> 
      <% consumption = consumption + carwing.e_consumption %> 
      <% regen = regen + carwing.e_regen %> 
      <% total = total + carwing.e_total %> 
      <% distance = distance + carwing.distance %> 
      <% economy = economy + carwing.economy %> 
      <% emissions = emissions + carwing.emission_reduction %> 
     <% else %> 
      <tr> 
      <td class="nowrap"><%= sumdate %></td> 
      <td><%= trips %></td> 
      <td><%= consumption %></td> 
      <td><%= regen %></td> 
      <td><%= total %></td> 
      <td><%= distance %></td> 
      <td><%= economy %></td> 
      <td><%= emissions %></td> 
      </tr> 
      <% trips = 1 %> 
      <% consumption = carwing.e_consumption %> 
      <% regen = carwing.e_regen %> 
      <% total = carwing.e_total %> 
      <% distance = carwing.distance %> 
      <% economy = carwing.economy %> 
      <% emissions = carwing.emission_reduction %> 
      <% sumdate = carwing.date %> 
     <% end %> 
    <% end %> 
    <tr> 
    <td class="nowrap"><%= sumdate %></td> 
    <td><%= trips %></td> 
    <td><%= consumption %></td> 
    <td><%= regen %></td> 
    <td><%= total %></td> 
    <td><%= distance %></td> 
    <td><%= economy %></td> 
    <td><%= emissions %></td> 
    </tr> 
    </tbody> 
</table> 

有一个更好的方法。

对此提出建议?

感谢您的帮助!

回答

0

一些小东西:

trips = trips + 1 
# is better written as: 
trips += 1 

ERB标签可以是多如:

<% if blah 
    do_something 
    something else 
    end %> 

如果要设置多个变量的值相同,则不需要重复他们的每一行例如:

trips = consumption = regen = 0 

是 - 这是次要的东西 - 但清理次要的东西,它会给你一个更好的形状o f你正在尝试做什么。如果你以描述性的伪代码给我们你的逻辑(所以我们不只是猜测你想做什么),那么我们也可以给你更好的代码结构。 :)

个人情况:我建议在您的控制器(甚至是您的carwing型号)设置所有这些数据之前,它的观点。我会用一个散列 - 是关键,其余所有是另一个散列,例如:

data = Hash.new({:trips => 0, :consumption => 0}) # google initialising hashes 
@carwings.each do |carwing| 
    data[carwing.date][:trips] += 1 
    data[carwing.date][:consumption] += carwing.e_consumption 
    # etc 
end 
+0

感谢您的信息! – Reddirt 2014-09-22 14:45:35