DEV Community

Cover image for ActiveRecord Calculations
Shaher Shamroukh
Shaher Shamroukh

Posted on

ActiveRecord Calculations

Let's talk about some useful methods that are very handy when we need to do some calculations to our database records.

So what is activerecord calculations?

ActiveRecord Calculations provide methods for calculating values of columns in the ActiveRecord models.

count Method

Let's start with a method that is widely knowing for simple count.

User.count 
#returns the number of users.
Enter fullscreen mode Exit fullscreen mode

Keep in mind that count is not always the most performant with that being said
this article demonstrates the difference between count, size, length.

But count has much more to offer 🔥 so let's see the different usage of count below 👇

User.count(:address)
# returns the count of all users whose address exist in our db.
Enter fullscreen mode Exit fullscreen mode
User.distinct.count(:city)
# returns the count of different cities we have in our db.
Enter fullscreen mode Exit fullscreen mode
User.group(:city).count
# returns a hash with each city and it's count.
#{ 'Cairo' => 5, 'Qina' => 3 }
Enter fullscreen mode Exit fullscreen mode

We can also do the above 👆 with multiple columns

Post.group(:status, :category).count
# {["draft", "business"]=>10, ["published", "art"]=>5}
Enter fullscreen mode Exit fullscreen mode

maximum Method

User.maximum(:age)
# 98
# returns the maximum value on the given column.
Enter fullscreen mode Exit fullscreen mode

minimum Method

User.minimum(:age)
# 18
# returns the minimum value on the given column.
Enter fullscreen mode Exit fullscreen mode

average Method

User.average(:age)
# 27.5
# returns the average value on the given column.
Enter fullscreen mode Exit fullscreen mode

sum Method

User.sum(:age)
# 7845
# returns the sum of the values on the given column.
Enter fullscreen mode Exit fullscreen mode

ids Method

User.ids
# returns the users ids
Enter fullscreen mode Exit fullscreen mode

Summary

Please check out the documentation for reference.

I hope you found the article useful and enjoyed reading as much as i enjoyed writing it 😃.

Top comments (0)