Quantico
Quantico

Reputation: 2446

how to group by and sum in rails 4

I read the following post and this post but I am still having some implementation problems.

In am trying to extract all costs that belongs to a user within a certain trip and sum their values based on their type(exchange_id). For example, a user can add a cost of 5$ , another cost of 10$ and a third cost of 50euro. I am trying to get [15$,50euro]

I have the following code @trip.costs.where(user_id: current_user).group("exchange_id")), but I don't know how to go from here and extract just the cost's value and sum it

Thank you

Upvotes: 8

Views: 23814

Answers (2)

@trip.costs
     .where(user_id: current_user)
     .group("exchange_id")
     .sum(:the_field_you_want_to_sum_by)

Upvotes: 1

sites
sites

Reputation: 21795

@costs = @trip.costs.where(user_id: current_user).group("exchange_id"))
@costs_sum = @costs.sum('the_field_you_want_to_sum_by')
=> { "exchange_id_1" => sum_1, ... }

PS: there is a typo.

Upvotes: 23

Related Questions