在我的费用表中,我创建了一个变量来计算比率乘以小时,我可以成功地获得我的数字。但是,我需要计算表末尾每一行的总数。我的一个字段是“所有行的总数”。什么是最好的行动方针?有什么建议吗?在我的费用/index.html.erb文件中,这是我目前拥有的代码
<tbody>
<% @costs.each do |cost| %>
<tr>
<td><%= cost.mini_description %></td>
<td><%= cost.description %></td>
<td><%= cost.quantity %></td>
<td><%= cost.rate %></td>
<td><%= cost.total%><%=cost.cost_var%></td>
<td><%= cost.total_of_all_rows %></td>
<!--<td><%#= cost.job %></td>-->
<td><%= link_to 'Show', cost %></td>
<td><%= link_to 'Edit', edit_cost_path(cost) %></td>
<td><%= link_to 'Destroy', cost, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
<thead>
<tr>
<th>Total of all rows</th>
</tr>
</thead>
我已经修正了我的代码,但我仍然没有得到想要的结果,我的total_of_all_rows没有加起来的速率和数量的总和。我修订的守则是:
<tbody>
<% @costs.each do |cost| %>
<tr>
<td><%= cost.mini_description %></td>
<td><%= cost.description %></td>
<td><%= cost.quantity %></td>
<td><%= cost.rate %></td>
<td><%= cost.total%><%=cost.cost_var%></td>
<!--<td><%#= cost.job %></td>-->
<td><%= link_to 'Show', cost %></td>
<td><%= link_to 'Edit', edit_cost_path(cost) %></td>
<td><%= link_to 'Destroy', cost, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
</tbody>
<thead>
<tr>
<th>Total of all rows</th>
</tr>
</thead>
<tr>
<td><%= cost.total_of_all_rows %><%=Cost.sum(:total) %></td>
</tr>
<% end %>
<tbody>
</tbody>
</table>我对这个表的迁移是
class CreateCosts < ActiveRecord::Migration
def change
create_table :costs do |t|
t.string :mini_description
t.string :description
t.string :quantity
t.string :rate
t.string :total
t.string :total_of_all_rows
t.references :job, index: true
t.timestamps
end
end结束
发布于 2014-06-12 18:21:35
1)不要将total_of_all_rows存储在数据库中,只要它是可变的,您就必须用每个新条目更新它。2)删除迁移栏。
3)你认为:
<tbody>
<% @costs.each do |cost| %>
<tr>
<td><%= cost.mini_description %></td>
<td><%= cost.description %></td>
<td><%= cost.quantity %></td>
<td><%= cost.rate %></td>
<td><%= cost.total%><%=cost.cost_var%></td>
<!--<td><%#= cost.job %></td>-->
<td><%= link_to 'Show', cost %></td>
<td><%= link_to 'Edit', edit_cost_path(cost) %></td>
<td><%= link_to 'Destroy', cost, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
</tbody>
<thead>
<tr>
<th>Total of all rows</th>
</tr>
</thead>
<tr>
<td><%= @costs.sum(:total) %></td>
</tr>
<% end %>
<tbody>如果您仍然想存储以下值:
class Cost < ActiveRecord::Base
after_save :update_totals
def update_totals
Item.all.each {|x| x.total_of_all_rows = Item.sum(:total)
end
endhttps://stackoverflow.com/questions/24191031
复制相似问题