我正在编写第一个按日期汇总数据的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 :(得分:0)
一些小事:
trips = trips + 1
# is better written as:
trips += 1
erb标签可以是多行的,例如:
<% if blah
do_something
something else
end %>
如果要将多个变量设置为相同的值,则无需在每行重复它们,例如:
trips = consumption = regen = 0
是的 - 这是次要的东西 - 但要清理一些小东西,它会让你更好地了解你想要做的事情。
也许如果你在描述性伪代码中给我们你的逻辑(所以我们不只是猜测你想要做什么),那么我们也可以为你的代码提供更好的结构。 :)
就个人而言:我建议您在控制器(甚至是carwing
型号)中设置所有这些数据,然后才能进入视图。我会使用哈希 - carwnig.date
是关键,剩下的就是另一个哈希,例如:
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