Managers would love that. Active Record provides nice, simple and powerful methods for counting things we have in our database. The simplest one is count or size:

User.count
User.where(first_name: "Nick").count

Average

Calculating the average value of given column is also super easy. It’s all about calling average and passing the desired column:

User.average(:salary)
User.where(first_name: "Nick").average(:salary)

Sum

You don’t have to iterate over all users to sum their salary, you can do it on database level using the sum method and passing column name:

User.sum(:salary)
User.where(first_name: "Nick").sum(:salary)

Want to receive useful tips, information about new Ruby gems and articles on a daily basis? Make sure you follow me and say hello!

Maximum

If you want to get the highest salary you don’t have to order by salary and select one user, you can use the maximum method:

User.maximum(:salary)
User.where(first_name: "Nick").maximum(:salary)

Minimum

If you want to find what salary is the lowest you can use the minimum method:

User.minimum(:salary)
User.where(first_name: "Nick").minimum(:salary)

Grouping

Let’s switch to more complicated operations. You can easily combine group with all of the mentioned functions. It will give you hash instead of a collection of objects.

User.group("users.location").average(:salary)

Above code produces hash including average salary for each location, useful, is not it?

Counting associations

Counting association seems to be a problematic part quite often. Let’s assume that each user can have many comments. Our goal is to show comments count for each user:

User.joins(:comments).group("users.name").count("comments.id")

It’s simple as that.

Want to become a better Rails developer?
Download for free the Introduction Rails patterns book and dive into the world of refactoring and easy-testable Ruby code today.
Join over 1,000 developers already subscribed to my newsletter and download the book. You can unsubscribe anytime:

Subscribe and get the book!