简体   繁体   English

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

[英]Rails - operations on multiple attributes of the same record

Given a Review model and a reviews table defined as follow: 给定一个Review模型和一个reviews表,定义如下:

 id | avg_rating | reviews_count
---------------------------------
  1 |          4 |            12
  2 |          5 |             2
  3 |          1 |             9
  4 |          3 |             1

I need to calculate a weighted_rating; 我需要计算一个weighted_rating; currently I do: 目前我正在:

sum = 0

Review.all.each do |review|
  sum = sum + review.avg_rating * review.reviews_count
end

weighted_rating = sum / Review.sum(:reviews_count)

Is there a cooler & functional way to get this done in Rails? 有没有一种更酷且实用的方法可以在Rails中完成此工作?

使用@Sujay的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM