I've looked at resources to know how to find the average with RoR built-in average
ActiveRecord::Calculations. I've also looked online for ideas on how to calculate averages: Rails calculate and display average.
But cannot find any reference on how to calculate the average of a set of elements from the database column.
In the controller:
@jobpostings = Jobposting.all
@medical = @jobpostings.where("title like ? OR title like ?", "%MEDICAL SPECIALIST%", "%MEDICAL EXAMINER%").limit(4).order('max_salary DESC')
@medical_salary = "%.2f" % @medical.average(:max_salary).truncate(2)
@medical returns:
CITY MEDICAL SPECIALIST
220480.0
CITY MEDICAL EXAMINER (OCME)
180000.0
CITY MEDICAL SPECIALIST
158080.0
CITY MEDICAL SPECIALIST
130000.0
I want to find the average of :max_salary
(each one is listed correctly under the job title). I use @medical_salary = "%.2f" % @medical.average(:max_salary).truncate(2)
to convert the BigDecimal number and find the average of :max_salary
from @medical
which I thought would be limited to the top 4 displayed above.
But the result returned is: 72322.33
, which is the average of the entire column (I checked), instead of the top 4.
Do I need to add another condition? Why does the average of @medical
return the average of the entire column?
Any insight would help. Thanks.