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.
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.
User.distinct.count(:city)
# returns the count of different cities we have in our db.
User.group(:city).count
# returns a hash with each city and it's count.
#{ 'Cairo' => 5, 'Qina' => 3 }
We can also do the above 👆 with multiple columns
Post.group(:status, :category).count
# {["draft", "business"]=>10, ["published", "art"]=>5}
maximum
Method
User.maximum(:age)
# 98
# returns the maximum value on the given column.
minimum
Method
User.minimum(:age)
# 18
# returns the minimum value on the given column.
average
Method
User.average(:age)
# 27.5
# returns the average value on the given column.
sum
Method
User.sum(:age)
# 7845
# returns the sum of the values on the given column.
ids
Method
User.ids
# returns the users ids
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)