Skip to content

Commit

Permalink
Merge pull request #13236 from jetthoughts/13230_type_cast_bug_in_agr…
Browse files Browse the repository at this point in the history
…_functions

Fix type cast on group sum with custom expression
Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information
senny committed Dec 10, 2013
1 parent ea722e1 commit f5a0524
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
16 changes: 16 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
* Use the right column to type cast grouped calculations with custom expressions.

Fixes #13230.

Example:

# Before
Account.group(:firm_name).sum('0.01 * credit_limit')
# => { '37signals' => '0.5' }

# After
Account.group(:firm_name).sum('0.01 * credit_limit')
# => { '37signals' => 0.5 }

*Paul Nikitochkin*

* Support deprecated finder options when performing calculations
on an association.

Expand Down
4 changes: 3 additions & 1 deletion activerecord/lib/active_record/relation/calculations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,9 @@ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
}
key = key.first if key.size == 1
key = key_records[key] if associated
[key, type_cast_calculated_value(row[aggregate_alias], column_for(column_name), operation)]

column_type = calculated_data.column_types.fetch(aggregate_alias) { column_for(column_name) }
[key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)]
end]
end

Expand Down
4 changes: 4 additions & 0 deletions activerecord/test/cases/calculations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,10 @@ def test_sum_should_return_valid_values_for_decimals
assert_equal 19.83, NumericData.sum(:bank_balance)
end

def test_should_return_type_casted_values_with_group_and_expression
assert_equal 0.5, Account.group(:firm_name).sum('0.01 * credit_limit')['37signals']
end

def test_should_group_by_summed_field_with_conditions
c = Account.where('firm_id > 1').group(:firm_id).sum(:credit_limit)
assert_nil c[1]
Expand Down

0 comments on commit f5a0524

Please sign in to comment.