给定Review
模型和reviews
表定义如下:
id | avg_rating | reviews_count
---------------------------------
1 | 4 | 12
2 | 5 | 2
3 | 1 | 9
4 | 3 | 1
我需要计算一个加权计算;目前我这样做:
sum = 0
Review.all.each do |review|
sum = sum + review.avg_rating * review.reviews_count
end
weighted_rating = sum / Review.sum(:reviews_count)
有冷却器吗?在Rails中完成这项工作的功能方法?
答案 0 :(得分:1)
使用@Sujay的appraoch:
Review.sum("avg_rating * reviews_count") / Review.sum(:reviews_count)