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?
You can use the
groupmethod.For each specialty:
This will return an
OrderedHashwhich key is thespecialtycolumn specified ingroupand value is the corresponding average amountsFor each client: