FattRyan
FattRyan

Reputation: 896

Rails 3 create and average multiple arrays

I have two models Clients and Reports. A Client has_many Reports and a Report belongs_to a Client. A Client has a :specialty attribute (doctor, dentist, lawyer) and a Report has an :amount attribute. There are 4 Reports generated per year on calendar quarters for each Client.

What I want to do is to be able to average the :amounts over the entries for a given :specialty, say lawyers. I can get one big array with these values from this particular :specialty like this:

Quarter.includes(:client).where('clients.specialty=?','Lawyer').map(&:amounts)%>

I'm wondering if there's a way to print an array for each Client with that :specialty, and then average them in another array. Do I use a loop here like this:

<% Quarter.includes(:client).where('clients.specialty=?', 'Lawyer').each do |c| %>
<%= c.amount  %>
<% end %>

If so, how do I separate it out so that instead of just one huge array, they are separate based on the client that it belongs to?

Upvotes: 0

Views: 464

Answers (1)

ShiningRay
ShiningRay

Reputation: 1008

You can use the group method.

For each specialty:

Quarter.includes(:client).group('clients.specialty').average('quarters.amounts')

This will return an OrderedHash which key is the specialty column specified in group and value is the corresponding average amounts

For each client:

Quarter.includes(:client).group('clients.id').average('quarters.amounts')

Upvotes: 2

Related Questions