diff --git a/lib/groupdate/magic.rb b/lib/groupdate/magic.rb index 5c7167f..550dd9a 100644 --- a/lib/groupdate/magic.rb +++ b/lib/groupdate/magic.rb @@ -132,11 +132,13 @@ module Groupdate count = begin - if method == :group_calc - Hash[ relation.select("#{relation.group_values[@group_index]} AS #{@field}", "#{args[0]} AS calculation").group("#{relation.group_values[@group_index]}").map{|record| [record.send(@field), record.calculation] } ] - else - Hash[ relation.send(method, *args, &block).map{|k, v| [multiple_groups ? k[0...@group_index] + [cast_method.call(k[@group_index])] + k[(@group_index + 1)..-1] : cast_method.call(k), v] } ] - end + calculation = + if method == :group_calc + Hash[ relation.group("#{relation.group_values[@group_index]}").pluck("#{relation.group_values[@group_index]} AS #{@field}, #{args[0]} AS calculation") ] + else + relation.send(method, *args, &block) + end + Hash[ calculation.map{|k, v| [multiple_groups ? k[0...@group_index] + [cast_method.call(k[@group_index])] + k[(@group_index + 1)..-1] : cast_method.call(k), v] } ] rescue NoMethodError raise "Be sure to install time zone support - https://github.com/ankane/groupdate#for-mysql" end diff --git a/test/test_helper.rb b/test/test_helper.rb index 8ad9331..d9dd63b 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -789,6 +789,16 @@ module TestGroupdate assert_equal 15, User.group_by_day(:created_at).group_calc("SUM(score) * 1.0 / COUNT(*)")[utc.parse("2014-05-01 00:00:00 UTC")] end + def test_group_calc_multiple_groups + create_user "2014-05-01 00:00:00 UTC", 10 + create_user "2014-05-01 00:00:00 UTC", 20 + expected = { + [10, utc.parse("2014-05-01 00:00:00 UTC")] => 10, + [20, utc.parse("2014-05-01 00:00:00 UTC")] => 20 + } + assert_equal expected, User.group(:score).group_by_day(:created_at).group_calc("SUM(score) * 1.0 / COUNT(*)") + end + # helpers def assert_format(method, expected, format, options = {}) -- libgit2 0.21.0