开发者

How to add values from table columns?

Hi i have a table where i list different values. Now i want to add a total values to my table that counts the values from each column and adds it to a column with the total value. How do I do this? And is it possible to do this in a simple way in the view, or am I bound to do it in the model? Thanks for any help!

<div class="chart-data">
  <table>
    <caption>Data</caption>
    <thead>
      <tr>
        <% statistic.column_titles.each do |column| %>
          <开发者_运维技巧;th><%= column %></th>
        <% end %>
        <th>Total</th>
      </tr>
    </thead>
    <tbody>      
      <% statistic.rows.each do |row| %>
        <tr>
          <th scope="row"><%= row.title %></th>
          <% row.data.each do |column| %>
            <td><%= column %></td>
            <% end %>
        </tr>
          <------- Here i want to have the code that sums the values from the columns above to form the 'Total'
      <% end %>
    </tbody>
  </table>  
</div>


The simple solution would be to maintain a variable that sums up the column, then use it for the total at the end.


class Row < ActiveRecord::Base
  def total_spent
    sum(:data)
  end
end

<tbody>      
  <% @rows.each do |row| %>
    <tr>
      <th scope="row"><%= row.title %></th>
      <% row.data.each do |column| %>
        <td><%= column %></td>
      <% end %>
    </tr>
    <td><% row.total_spent %></td>
  <% end %>
</tbody>

Assuming of course that row is a model you could move this logic inside the row model. You may cache the page as well if you like.


If your data is the result of an ActiveRecord query against a database you could ask the database to do the work of summing all the columns. It would be one additional query but would run very quickly as that's something databases are designed to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜