“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: .

“Changing the class of a div using rails NOT JS” Installing ActiveMQ

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 )

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

Trackback this post  |  Subscribe to the comments via RSS Feed


Recent Posts

Pages


Follow

Get every new post delivered to your Inbox.