提交 36bd52b4 编写于 作者: S Sean Griffin

Don't use `Column` for type casting in Relation calculations

上级 dccf6da6
......@@ -273,7 +273,7 @@ def execute_simple_calculation(operation, column_name, distinct) #:nodoc:
row = result.first
value = row && row.values.first
column = result.column_types.fetch(column_alias) do
column_for(column_name)
type_for(column_name)
end
type_cast_calculated_value(value, column, operation)
......@@ -336,14 +336,14 @@ def execute_grouped_calculation(operation, column_name, distinct) #:nodoc:
Hash[calculated_data.map do |row|
key = group_columns.map { |aliaz, col_name|
column = calculated_data.column_types.fetch(aliaz) do
column_for(col_name)
type_for(col_name)
end
type_cast_calculated_value(row[aliaz], column)
}
key = key.first if key.size == 1
key = key_records[key] if associated
column_type = calculated_data.column_types.fetch(aggregate_alias) { column_for(column_name) }
column_type = calculated_data.column_types.fetch(aggregate_alias) { type_for(column_name) }
[key, type_cast_calculated_value(row[aggregate_alias], column_type, operation)]
end]
end
......@@ -370,24 +370,20 @@ def column_alias_for(keys)
@klass.connection.table_alias_for(table_name)
end
def column_for(field)
def type_for(field)
field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split('.').last
@klass.columns_hash[field_name]
@klass.type_for_attribute(field_name)
end
def type_cast_calculated_value(value, column, operation = nil)
def type_cast_calculated_value(value, type, operation = nil)
case operation
when 'count' then value.to_i
when 'sum' then type_cast_using_column(value || 0, column)
when 'sum' then type.type_cast_from_database(value || 0)
when 'average' then value.respond_to?(:to_d) ? value.to_d : value
else type_cast_using_column(value, column)
else type.type_cast_from_database(value)
end
end
def type_cast_using_column(value, column)
column ? column.type_cast_from_database(value) : value
end
# TODO: refactor to allow non-string `select_values` (eg. Arel nodes).
def select_for_count
if select_values.present?
......
......@@ -53,11 +53,6 @@ def test_should_return_nil_as_average
assert_nil NumericData.average(:bank_balance)
end
def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
assert_equal 0, NumericData.all.send(:type_cast_calculated_value, 0, nil, 'avg')
assert_equal 53.0, NumericData.all.send(:type_cast_calculated_value, 53, nil, 'avg')
end
def test_should_get_maximum_of_field
assert_equal 60, Account.maximum(:credit_limit)
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册