0

我有一个 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_ratingRating.find(:all, :conditions => ["rating_set = ? and product_id =?", 45 ,product.id]).

4

1 回答 1

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
于 2013-03-05T04:45:30.873 回答