dannymcc
dannymcc

Reputation: 3814

Get sum of record attributes when grouping in Rails?

I am grouping mileage entries by month in my Rails 3.2 application:

mileages_controller.rb

  def index
    @mileages = Mileage.find_all_by_user_id(current_user.id)
    @mileages_months = Mileage.find_all_by_user_id(current_user.id).group_by { |t| t.created_at.beginning_of_month }

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @mileages }
    end
  end

index.html.erb

<% @mileages_months.sort.each do |month, mileages| %>
  <h4><%= month.strftime('%B %Y') %></h4>
  <p>Total miles <strong><%= mileages.miles.sum %></strong>.</p>
  <table>
    <tr>
      <th>Name</th>
      <th>Miles</th>
      <th>Start</th>
      <th>Destination</th>
      <th></th>
    </tr>
      <% for mileage in mileages %>
        <tr>
          <td><%= mileage.name %></td>
          <td><%= mileage.miles %></td>
          <td><%= mileage.start %></td>
          <td><%= mileage.end %></td>
          <td><%= link_to 'Show', mileage %></td>
        </tr>
      <% end %>
</table>
<% end %>

As you can see, I am trying to sum the total miles in each month using <%= mileages.miles.sum %>. This won't work - but <%= mileages.first.miles %> correctly shows the first entry's miles for each month.

What is the correct way of totalling up the miles column for each month?

Upvotes: 0

Views: 554

Answers (1)

Amit Thawait
Amit Thawait

Reputation: 5292

Well you can create a helper method(to keep this logic seperate from the view) in the mileage_helper as :

def sum_mileges(mileages)
  mileages.map(&:miles).sum
end

and then calling it in the view as

<p>Total miles <strong><%= sum_mileges(mileages) %></strong>.</p>

OR

you can do it directly as :

<p>Total miles <strong><%= mileages.map(&:miles).sum %></strong>.</p>

Upvotes: 1

Related Questions