This post originated from an RSS feed registered with Ruby Buzz
by Bob Silva.
Original Post: ActiveRecord Calculations
Feed Title: Rails Video Tutorials
Feed URL: http://www.railtie.net/xml/rss/feed.xml
Feed Description: A growing collection of screencasts that show you how to use the many facets of the wonderful world of rails.
Rick Olson'sCalculations Plugin (which is now part of core) is great as long as you only need to perform a calculation on one column in your model. I had a need to sum two columns in a result set and after talking with Rick on IRC, started to modify his Calculations Plugin to accept a hash of {:calc => :column} pairs. Time was of the essence though so I found a different way to do it using AR. The examples below don't really have any wow factor, but they may be helpful to someone.
In the example below, it inner joins table (ModelB) and groups by a column (group_field) from that table, just to show how it might be done.
The magic is the :select option. It allows you to define what goes into the SQL statement (SELECT :select FROM ...). The :readonly attribute on the find call, is to prevent you from trying to modify the record since it is not a fully loaded AR record set.
Now that you have your recordset, you can use your calculated columns like any other AR attribute. In this case, @model_a.column_a. If you build more advaned reporting or charts into your applications, you will find yourself using this method a lot.