Counting things in Rails

Ruby on Rails / Active Record

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)

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.