I'd normally let the database do the work, and create the appropriate
SQL statement within the controller. Off the top of my head, within
your SalesOrder controller:

def ship_date_sum(@month, @year)
  sum = SalesOrder.find_by_sql("SELECT SUM(amount) FROM SalesOrders
WHERE month(ship_date) = ? AND year(ship_date) = ?", @month, @year)
  return sum

Then just call it as SalesOrder.ship_date_sum(@month,@year) from
wherever you want to use it.

(Yep, I'm almost certain that isn't 100% correct, but I'm typing this
while I'm on hold for a phone call and hopefully you get the gist of

Doing the SELECT SUM(amount) ... in SQL will force the database to do
the work rather than your app, and will return a minimal amount of
data to your app. It makes it easier to optimise your database later
(e.g. work out where to put indexes, in this case), gives you easier
scalability, consumes less memory on your Rails server, ... If you're
really pushed for performance, you could even create the SELECT SUM...
as a stored proc on your database server and get the result back

I'm all for getting the database to do as much work as possible, and
making sure my Rails code has as small a footprint as possible. Other
people prefer the Rails app to do all the work - Google for the pros
and cons of each approach if you're interested.



Dave M.