我正在试图平均做多个参数。对于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
对于多个参数,此命令不起作用:未初始化的常量
@ratingall = Commment.where(:camping_id => params[:id]).average(:service, :communication, :qualiteprix, :animation, :proprete, :situation).to_i
顺便说一下,这种方法不是DRY ......
答案 0 :(得分:2)
average只接受一个列名。
如果您想直接计算平均值,您可能需要编写SQL查询。
对于代码的DRYer版本:
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现在是一个Hash,例如{:service => 3,:communication => 2,...}
获得平均值:
@ratingall = @ratings.values.sum.to_f/ratings.size
要在您的视图中获得具体评分:
@ratings[:service]
迭代评级:
@ratings.each do |category,rating|
# Use category and rating variables.
end