“Sum/Avg method in Rails , save a query”
December 9, 2008 at 4:13 pm Leave a comment
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. Tags: .
Trackback this post | Subscribe to the comments via RSS Feed