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

  • Facebook
  • Google Bookmarks
  • email
  • NewsVine
  • Slashdot
  • Technorati
  • Yahoo! Buzz
  • BlinkList
  • Print
  • Propeller
Filed under: Programming — Tags: , , , , , , , — Aaron Murphy @ 12:36 pm on April 2, 2009

1 Comment

  1. This is great…Im going to have refactor some of my code.

    Comment by Chris Gunnels — April 2, 2009 @ 4:59 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment


Copyright © 2005-2010 PMA Media Group. All Rights Reserved . Online Degrees | Train for a Better Career | My Colleges and Careers Site Map