使用RubyonRails添加html
我有一个包含价格和数量字段的表。我想将价格*数量添加到最终添加到表中的每个项目的总计中 我的代码看起来像这样使用RubyonRails添加html,html,ruby-on-rails,ruby,Html,Ruby On Rails,Ruby,我有一个包含价格和数量字段的表。我想将价格*数量添加到最终添加到表中的每个项目的总计中 我的代码看起来像这样 <table> <thead> <tr> <th width="200">Name</th> <th width="150">Price</th>
<table>
<thead>
<tr>
<th width="200">Name</th>
<th width="150">Price</th>
<th>Quantity</th>
<th width="150">Total</th>
</tr>
<% @item.each do |item| %>
<tr>
<td><%= item.name %></td>
<td><%= item.price %></td>
<td><%= item.quantity %></td>
<td><%= item.quantity * item.price %></td>
<td class="actions">
<% link_to("update", :class => 'action update') %>
<% link_to("X", :class => 'action delete') %>
</td>
</tr>
<% end %>
</thead>
</table>
名称
价格
量
全部的
“操作更新”)%%>
“操作删除”)%%>
我的总数是以标签的形式出现的。
我该怎么做?RoR中是否存在静态变量概念???您可以使用以下方法获得总计:
<% #= @item.inject{ |grand_total, quantity| grand_total + (quantity * cart.price) } %>
更新:
请忽略上面的代码行,这是为了给您展示一个示例。下面的代码示例应该可以解决您的问题
将下一行放在要显示总计的位置
<%= label_tag 'grand_total',
@item.inject(0) { |grand_total, item| grand_total + (item.quantity * item.price) } %>
@item.inject(0){| grand_total,item | grand_total+(item.quantity*item.price)}
将块应用于每个项
。在这种情况下,第一个参数grand_total
首先被指定为0
的初始值。这是通过inject(0)
完成的
然后,该块开始将(item.quantity*item.price)
累积到grand_total
中,这是inject
返回的最终值
希望这有意义。您应该在表中添加字段grand_total,并在项目模型中创建回调。每次创建新项时,此回调将在表中保存总计值
before_save : save_grand_total
def save_grand_total
self.grand_total = self.quantity * self.price
end
名称
价格
量
全部的
“操作更新”)%%>
“操作删除”)%%>
使用数据库进行这些操作如果您对此感到满意,请不要忘记接受答案。它将帮助贡献者。@user3040563,看来回答者已经提供了足够的代码让你自己去尝试,不是吗?这是不言自明的,真的。。。
<table>
<thead>
<tr>
<th width="200">Name</th>
<th width="150">Price</th>
<th>Quantity</th>
<th width="150">Total</th>
</tr>
<% grand_total=0 %>
<% @item.each do |item| %>
<tr>
<td><%= item.name %></td>
<td><%= item.price %></td>
<td><%= item.quantity %></td>
<td><%= item.quantity * item.price %></td>
<% grand_total+= item.quantity * item.price %>
<td class="actions">
<% link_to("update", :class => 'action update') %>
<% link_to("X", :class => 'action delete') %>
</td>
</tr>
<% end %>
</thead>
</table>