我有一个rake任务,我在其中计算一组产品的平均值,但是我无法计算和更新每个个人的属性。到目前为止我所拥有的:
task :calculate_rating => :environment do
total_rating = []
Product.find(:all, :joins => :rating_sets, :conditions => ["rating_set_id = ?", 45 ]).each do |product|
Rating.find(:all, :conditions => ["rating_set = ? and product_id =?", 45 ,product.id]).each do |ratings|
total_rating << ratings.rating
end
average = total_rating.inject(:+).to_f / total_rating.size
q = ProductRatingSet.find_by_product_id_and_rating_set_id(@product_id, 45)
q.update_attribute(:product_rating, average)
end
end
我试图基本找到平均值并更新product_rating
检索到的每个集合的Rating.find(:all, :conditions => ["rating_set = ? and product_id =?", 45 ,product.id])
。
答案 0 :(得分:0)
尝试将total_rating数组的初始化放在第一个循环中
Product.find(:all, :joins => :rating_sets, :conditions => ["rating_set_id = ?", 45 ]).each do |product|
total_rating = []
Rating.find(:all, :conditions => ["rating_set = ? and product_id =?", 45 ,product.id]).each do |ratings|
total_rating << ratings.rating
end
average = total_rating.inject(:+).to_f / total_rating.size
q = ProductRatingSet.find_by_product_id_and_rating_set_id(@product_id, 45)
q.update_attribute(:product_rating, average)
end