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

rails, Uncategorized

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.

@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

calculations, calculations in rails, sum, avg, minimum, rails


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s