Unique Marketing, Guaranteed Results.

You Don’t Need Custom SQL For Simple Aggregation Using ActiveRecord

April 2nd, 2009 by Aaron Murphy

ActiveRecord allows one to execute an SQL statement directly. I prefer to avoid any ActiveRecord code that uses too much SQL syntax. This way I won’t have to rework any code if the underlying database engine was changed. Some of the simple SQL functions that one may want to do with SQL syntax might be SUM, AVG, COUNT, etc. With ActiveRecord::Calculations::ClassMethods, one can avoid specialized syntax.

1
2
3
4
#returns the total count of all people
Person.count
# returns the total count of all people with an age over 26
Person.count(:conditions => "age > 26")

The following methods are available: average, count, maximum, minimum, sum


Copyright © 2005-2010 PMA Media Group. All Rights Reserved