ActiveRecord::Calculations will now use column-based type casting

ActiveRecord::Calculations is a great collection of methods that allow arithmetic operations to be performed right on the ActiveRecord attributes. These are the available methods:

  • average
  • calculate
  • count
  • ids
  • maximum
  • minimum
  • pluck
  • sum

Ideally, the expectation would be that the return type of these methods would be the same as the column type itself. However, a discrepancy in aggregation leads to Rails calling to_d on average aggregates from the database adapter. It could cause some inefficiencies in the code.

Before

Let’s assume we have a class called Product with attributes price as BigDecimal and rating as Float. Now, calling average on them would lead to some irregular errors.

Product.average(:price)
# => 17.96 (BigDecimal)

Product.average(:rating)
# => 4.3 (BigDecimal)
# The return type should be Float.

Unfortunately, the results are not harmonious with their data types.

After

With the latest changes in Rails 7, we can now expect harmonious results.

Product.average(:price)
# => 17.96 (BigDecimal)

Product.average(:rating)
# => 4.3 (Float)

This leads to better overall accuracy in calculations.

Need help on your Ruby on Rails or React project?

Join Our Newsletter