nicolaswecandoit nicolaswecandoit - 1 year ago 87
Ruby Question

Global average for multiple params

I m triying to do an average of multiple params. For 1 unique params all works perfectly but I can't do multiple params average. Can you help me ?

@ratingservice = Comment.where(:camping_id => params[:id]).average(:service).to_i
@ratingcommunication = Comment.where(:camping_id => params[:id]).average(:communication).to_i
@ratingqualiteprix = Comment.where(:camping_id => params[:id]).average(:qualiteprix).to_i
@ratinganimation = Comment.where(:camping_id => params[:id]).average(:animation).to_i
@ratingproprete = Comment.where(:camping_id => params[:id]).average(:proprete).to_i
@ratingsituation = Comment.where(:camping_id => params[:id]).average(:situation).to_i

For multiple params this command doesnt work : uninitialized constant

@ratingall = Commment.where(:camping_id => params[:id]).average(:service, :communication, :qualiteprix, :animation, :proprete, :situation).to_i

By the way this method isn't DRY for sure....

Answer Source

average only accepts one column name.

You'll probably have to write a SQL query if you want to calculate the average of the averages directly.

For a DRYer version of your code :

where_camping = Comment.where(:camping_id => params[:id])
ratings = [:service, :communication, :qualiteprix, :animation, :proprete, :situation].map{|key|
  [key, where_camping.average(key).to_i]

ratings is now a Hash with e.g. {:service => 3, :communication => 2, ...}

To get the average of averages:

@ratingall = ratings.values.sum.to_f/ratings.size
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download