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 expert help with Rails database work?

Saeloun is a Rails Foundation Contributing Member helping teams modernize, upgrade, scale, and maintain production Rails applications.

Our Expertise

  • Rails contributors
  • 500+ Technical Articles
  • Production Rails consulting
  • Performance Optimization

Services

  • Rails application development
  • Code Audits
  • Rails upgrades
  • Team Augmentation

Need help on your Ruby on Rails or React project?

Join Our Newsletter