The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
ActiveRecord Calculations

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Bob Silva

Posts: 94
Nickname: bobsilva
Registered: Feb, 2006

Bob Silva is a Rails Developer for the UMESD
ActiveRecord Calculations Posted: Apr 22, 2006 9:24 AM
Reply to this message Reply

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.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Bob Silva
Latest Posts From Rails Video Tutorials

Advertisement

Rick Olson's Calculations 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.

@model_a = ModelA.find(:all,
  :select => 'sum(column_a) as column_a, sum(column_b) as column_b, model_b.group_field', 
  :joins => 'inner join model_b on model_a.id = model_b.model_a_id', 
  :group => 'model_b.group_field', 
  :conditions => ['column_a=?', column_a_value],
  :readonly => true)


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.

Read: ActiveRecord Calculations

Topic: Globalize Ready for Testing on Rails 1.1 Previous Topic   Next Topic Topic: RadRails was SadRails (for a little while)

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use