Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 532
Quantico Avatar asked Oct 27 '13 16:10

Quantico


1 Answers

@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.

like image 59
sites Avatar answered Nov 19 '22 15:11

sites