2014-09-22 58 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