0

我有一個rake任務,我正在計算一組產品的平均值,但是我無法計算和更新每個集合中的個人的屬性。我有什麼至今:Rails計算平均值

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

試圖把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 
+0

這仍然好像total_rating被視爲值的單個陣列內。 – Yogzzz 2013-03-05 06:24:06