views:

104

answers:

2

I am doing a find in Rails model as follows:

@jobs = Job.find(:all, :conditions => ["job_id = ?", params[:id]])

The result of this query also brings back data from an associated model JobResponses (there are multiple JobResponses for each Job record). Once I have the JobResponse results I am calculating a number of different averages/medians etc for each set of Job results.

One of the columns returned in the JobResponses is company_id - so therefore I might get back 10 job responses (4 from Company A, 2 from Company B, 2 from Company C and 1 each from Company D & E) - 5 distinct companies.

How can I calculate/display the number of distinct companies that returned a result for JobResponses?

+1  A: 

If i'm understand clearly, try following to get number of distinct companies: @jobs.map(&:job_responses).flatten.map(&:company_id).uniq.size

thaold
A: 

Perhaps, plain sql?

@jobs = Job.find_by_sql('select job.*, count(jr.id) as distinct_responses from job, job_responses jr where jr.job_id = job.id group by job.id')

each element of @jobs now have distinct_responses accessor

artemave