我正在尝试做一个平均多个参数。对于一个唯一的params,所有工作都很完美,但我不能做多个params平均值。你能帮我吗?
@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顺便说一句,这种方法不一定干.
发布于 2016-11-17 22:09:13
平均值只接受一个列名。
如果要直接计算平均值的平均值,则可能需要编写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@评级现在是一个哈希,例如{:=> 3,:communication => 2,.}
要得到平均数的平均值:
@ratingall = @ratings.values.sum.to_f/ratings.size若要在您的观点中获得特定的评级:
@ratings[:service]要迭代评级:
@ratings.each do |category,rating|
# Use category and rating variables.
endhttps://stackoverflow.com/questions/40665656
复制相似问题