aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activerecord/CHANGELOG2
-rw-r--r--activerecord/lib/active_record/calculations.rb1
-rw-r--r--activerecord/test/calculations_test.rb11
3 files changed, 14 insertions, 0 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG
index aee47c652e..ab441ac9e3 100644
--- a/activerecord/CHANGELOG
+++ b/activerecord/CHANGELOG
@@ -1,5 +1,7 @@
*SVN*
+* Allow ordering of calculated results and/or grouped fields in calculations [solo@gatelys.com]
+
* Dynamically set allow_concurrency. #4044 [Stefan Kaes]
* Added Base#to_xml that'll turn the current record into a XML representation [DHH]. Example:
diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb
index 8988ebf4e8..6c5ae3edca 100644
--- a/activerecord/lib/active_record/calculations.rb
+++ b/activerecord/lib/active_record/calculations.rb
@@ -151,6 +151,7 @@ module ActiveRecord
add_conditions!(sql, options[:conditions])
sql << " GROUP BY #{options[:group_field]}" if options[:group]
sql << " HAVING #{options[:having]}" if options[:group] && options[:having]
+ sql << " ORDER BY #{options[:order]}" if options[:order]
sql.join
end
diff --git a/activerecord/test/calculations_test.rb b/activerecord/test/calculations_test.rb
index e724695406..8f4a3de17a 100644
--- a/activerecord/test/calculations_test.rb
+++ b/activerecord/test/calculations_test.rb
@@ -37,6 +37,17 @@ class CalculationsTest < Test::Unit::TestCase
assert_equal 60, c[2]
end
+ def test_should_order_by_grouped_field
+ c = Account.sum(:credit_limit, :group => :firm_id, :order => "firm_id")
+ assert_equal [nil, 1, 2, 6], c.keys
+ end
+
+ def test_should_order_by_calculation
+ c = Account.sum(:credit_limit, :group => :firm_id, :order => "sum_credit_limit desc, firm_id")
+ assert_equal [105, 60, 50, 50], c.keys.collect { |k| c[k] }
+ assert_equal [6, 2, nil, 1], c.keys
+ end
+
def test_should_group_by_summed_field_having_condition
c = Account.sum(:credit_limit, :group => :firm_id,
:having => 'sum(credit_limit) > 50')