Scott Rice
Scott Rice

Reputation: 1165

How to use ActiveRecord calculations with relations

I am trying to make an admin dashboard that shows an administrator relevant statistics about the site. For example, given a company has many users, finding the average number of users per company, or the maximum number of users a company has.

I have found activerecord::calculations, which seems to do most of what I want, but as far as I can tell, it doesn't let you do anything with relations. How would I go about finding counts or averages that are grouped by relations?

Upvotes: 0

Views: 197

Answers (1)

Matthew Rudy
Matthew Rudy

Reputation: 16834

You have to think of it in terms of the User.

The simplest way would be

# get a hash of company_ids and user counts
User.group(:company_id).count

But then you'll have to load the Companies and match them up.

Then you could try and do

user_counts = User.group(:company_id).count

company_users = Company.all.map{|company| user_counts[company.id]}

# the maximum
company_users.max

# the average
company_users.sum.to_f / company_users.length

Upvotes: 1

Related Questions