1

我有一种方法可以计算给定记录集的平均值:

input = params[:recommendation_ratings].values  # The params are sent from radio_tags in my view.

input.each do |mini_params|
rating_id = mini_params[:rating_id]
l = Rating.find(rating_id) #Find record on Rating table. 
l.rating #Get value associated with rating_id
total_rating = []
total_rating << l.rating
average = total_rating.inject{ |sum, el| sum + el }.to_f / total_rating.size
puts average
end

l.rating 未附加到 total_rating 数组。看跌平均值打印为:

3.0
3.0
3.0
3.0
3.0

如何将返回的每个评级附加到数组中以计算平均值和其他数学函数。

4

3 回答 3

6

尝试:

total_rating = []    
input.each do |mini_params|
  rating_id = mini_params[:rating_id]
  l = Rating.find(rating_id) #Find record on Rating table. 
  total_rating << l.rating      
end
average = total_rating.sum / total_rating.size.to_f
于 2013-02-08T06:38:52.940 回答
2

这应该可以解决您的问题,但有更好的方法

total_rating = []    
input.each do |mini_params|
  rating_id = mini_params[:rating_id]
  l = Rating.find(rating_id) #Find record on Rating table. 
  total_rating << l.rating
  average = total_rating.inject(:+).to_f / total_rating.size
  puts average
end

因此,给定一个 id 数组,请尝试以下操作

Rating.where(id: mini_params[:rating_id]).average(:rating)

更新:修复单行版本

rating_ids = input.map { |mini_params| mini_params[:rating_id] }
Rating.where(id: rating_ids).average(:rating)
于 2013-02-08T06:31:49.040 回答
0

您需要首先获得您想要平均的所有评级。我假设您已经这样做了,并且所有这些评级都存储在total_rating. 然后您需要将特定评级添加到该数组:

rating_id = mini_params[:rating_id]
l = Rating.find(rating_id)
total_rating << l
average = total_rating.sum.to_f / total_rating.size
puts average
于 2013-02-08T06:29:03.827 回答