“Sum/Avg method in Rails , save a query”

December 9, 2008

Ever wondered about the Calculations in Rails, I used to use the group_by in SQL or select to do many calculations while fetching the results , but sometimes Rails doesnt allow to use group etc , like when we are doing AJAX calls in v2.1.0 of rails .

Then Joejeet helped me to get the following calculations methods , it was so beautiful that my 3 line of code was convered to 1 single line.

Code
@rating_sum = Rating.sum(‘rating’, :conditions =>["rateable_id = ? and rateable_type = ?", @rating.rateable_id, @rating.rateable_type])

There are other methods like Avg,minimum, max,count etc available under
Module: ActiveRecord::Calculations::ClassMethods

, , , , ,

Entry Filed under: ruby on rails. .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

Tags

Active Record australian gp calendar date select capistrano capitalize debugging Debugging in rails edge rails formula 1 For those who dont want to update the prototype.js fun Fun baby fun google html in join javascript linus vs windows compatibility linux logging love song malaysian gp 2008 results melbourne migrations music mysql plugin poetry rails regexp regular expression results formula 1 opening race romantic poetry ror Ruby ruby on rails safe html sms song SQL string case handler for strings syantax syntax error for migrations on linux Text Area they can checkout 1.8.3 of the calender date select

Blogroll

Pages