Count with ActiceRecord

published on NOV 1, 2018

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.where(first_name: "Nick").count


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

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


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.where(first_name: "Nick").sum(:salary)


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.where(first_name: "Nick").maximum(:salary)


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

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


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


It’s simple as that.

Tagged: Ruby Ruby on Rails

Cookies help us deliver our services. By using our services, you agree to our use of cookies.