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:

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

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

Tags: , ,     Posted in Development

Rate this article:
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Related Content


Leave a Reply