【问题标题】:addition in html using ruby on rails在 html 中使用 ruby​​ on rails 添加
【发布时间】:2013-12-17 15:19:15
【问题描述】:

我有一张包含价格和数量字段的表格。我想将价格 * 数量添加到我最终添加到表格中的每个项目的总计中。

我的代码如下所示。

<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中有静态变量的概念吗??

【问题讨论】:

  • 使用数据库进行这些操作
  • 如果您对此感到满意,请不要忘记接受答案。它将帮助贡献者。

标签: html ruby-on-rails ruby


【解决方案1】:

您应该在表中添加字段 grand_total 并在 Item 模型中创建回调。此回调将在每次创建新项目时将总计的值保存在表中。

before_save : save_grand_total

def save_grand_total
  self.grand_total = self.quantity * self.price
end

【讨论】:

    【解决方案2】:

    您可以使用Enumerable#inject 得到总计,如下所示:

    <% #= @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) } 将块应用于每个item。在这种情况下,第一个参数grand_total 首先分配了初始值0。这是通过inject(0) 完成的。

    然后该块开始将(item.quantity * item.price) 累积到grand_total 中,这是inject 返回的最终值。

    希望这是有道理的。

    【讨论】:

    • @user3040563,看来回答者已经提供了足够的代码让您自己尝试一下,不是吗?这很不言自明,真的......
    【解决方案3】:
    <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>
    

    【讨论】:

      猜你喜欢
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多