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

Foreign Key Migrations Plugin

April 2nd, 2009 by Chuck Wood

I worked on a plugin yesterday that would include all of our migration helpers. You can find it on github. Currently, it only does foreign keys work, but eventually, I’d like to have it add unique indexes on columns defined with a :unique => true attribute in the ActiveRecord migration. But for right now, here’s how to use it:

Adding a foreign key that references the id column in another table:

# The column 'id' is assumed in the referenced table.
add_foreign_key :table1, :table2_ref, :table2

Read the rest of this entry »

ActiveRecord Destroy vs. Delete

April 2nd, 2009 by Chuck Wood

I’ve been reading “Pro ActiveRecord” by Kevin Marshall, Chad Pytel, and Jon Yurek. They explained in the book the difference between the delete and destroy methods, which is something I had never really seen clarified anywhere. I’ve discussed it with several Rails developers and have gotten varying opinions.

Read the rest of this entry »


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