Rails - 对同一记录的多个属性的操作

时间:2018-03-07 12:28:38

标签: ruby-on-rails functional-programming

给定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中完成这项工作的功能方法?

1 个答案:

答案 0 :(得分:1)

使用@Sujay的appraoch:

Review.sum("avg_rating * reviews_count") / Review.sum(:reviews_count)