私は複数のパラメータの平均を実行しようとしています。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
ちなみに、この方法は確かにドライではありません。
平均は1つの列名のみを受け入れます。
平均の平均を直接計算する場合は、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は、たとえば{: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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加