2016-11-17 73 views
1

我正在测量多个参数的平均值。对于1个独特的参数,所有作品都完美无缺,但我无法平均做多个参数。你可以帮我吗 ?多个参数的全球平均值

@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 

对于多PARAMS该命令不工作:未初始化不断

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

通过这种方法是不燥肯定的方式....

+0

个人而言,尚未尝试过。 'Comment.where(:camping_id => params [:id])。group(:service,...)'看看返回的东西然后得到总和/平均等...让我知道! – 7urkm3n

回答

2

average只接受一个列名。

如果要直接计算平均值的平均值,您可能必须编写SQL查询。

为您的代码的版本烘干机:

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

@ratings现在是例如哈希{:服务=> 3:通信=> 2,...}

为了得到平均的平均:

@ratingall = @ratings.values.sum.to_f/ratings.size 

要在视图中获取特定的评价:

@ratings[:service] 

要重复评级:

@ratings.each do |category,rating| 
    # Use category and rating variables. 
end 
+0

作品!谢谢 !!! – nicolaswecandoit

+0

还有一个问题,如果我想显示“服务”或其他参数的平均值单独如何在我的视图中可以这样的ID? – nicolaswecandoit

+0

查看更新的答案。 –