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.

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

### After

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

This leads to better overall accuracy in calculations.

Need help on your Ruby on Rails or React project?

Join Our Newsletter