user1374924
user1374924

Reputation: 1

Method to return sum of multiple columns in Rails ActiveRecord Model

I'm new to rails and ActiveRecord and wondering if there is a straightforward way to do below without having to create complicated Sql group by queries and passing params.

I have a model LineProduction with columns line_date (date), line_1 (integer), line_2(integer), line_3(integer).

I would like to create a method in my model to return daily_total of all lines grouped by date - daily_total(line_date) so that I can return the value in a table report for each row of the month. eg.

line_date line_1 line_2 line_3 daily_total

Thanks!

Upvotes: 0

Views: 255

Answers (1)

nickcen
nickcen

Reputation: 1692

You can take a look at this gem https://github.com/ankane/groupdate

LineProduction.group_by_date(:line_date).count
# {
#   2016-02-01 00:00:00 UTC => 50,
#   2013-02-02 00:00:00 UTC => 100,
#   2013-02-03 00:00:00 UTC => 34
# }

Upvotes: 0

Related Questions