Rails 2.1: Aggregate Expressions

It was (I think) possible in Rails prior to 2.1 to perform calculations like this:

total = Donation.sum(:amount)

I never used this functionality, so it’s news to me! But in any case, it’s quite useful; under the hood, it’s similar to a query like SELECT SUM(amount) FROM Donation d, albeit in a database-independent fashion.

In any case, Rails 2.1 takes this a step farther; you can specify a complex calculation for an aggregate function. For example, to calculate the aggregate sum of donations, you can do this:

total = Donation.sum("amount * amount")

…and Rails will calculate it for you! Something as complex as the standard deviation becomes a snap. Incidentally, Rails provides the following aggregate queries:

  • ActiveRecord.average
  • ActiveRecord.count (like COUNT(*))
  • ActiveRecord.maximum
  • ActiveRecord.minimum
  • ActiveRecord.sum

You can find the full details at the ActiveRecord/Calculations API.

This is one of several topics discussed in the Rails 2.1 eBook.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Comments are closed.