2009-11-24 68 views
0

我試圖計算平均值(mean)評級基於以下模型關聯一個類別中的所有條目...模型關係問題

class Entry < ActiveRecord::Base  
    acts_as_rateable 
    belongs_to :category 
    ... 
end 


class Category < ActiveRecord::Base 
    has_many :entry 
    ... 
end 


class Rating < ActiveRecord::Base 
    belongs_to :rateable, :polymorphic => true 
    ... 
end 

該評級模型是由acts as rateable插件處理,所以應課稅模型看起來像這樣...

module Rateable #:nodoc: 
    ... 

    module ClassMethods 
     def acts_as_rateable 
     has_many :ratings, :as => :rateable, :dependent => :destroy 
     ... 
     end 
    end 
    ... 
    end 

我該如何進行平均計算?這可以通過rails模型關聯來完成,還是必須使用SQL查詢?

回答

1

average方法也可能是你在找什麼。以下是如何在您的情況下使用它:

@category.entries.average('ratings.rating', :joins => :ratings) 
+0

我深知平均的方法,但我不知道如何將其應用於這種情況。我有興趣找到特定類別內所有條目的平均值(平均值)。 – crh

+0

當然!完善!謝謝。我開始覺得我瘋了。 – crh

0

您可以在模型上使用named_scope或自定義方法嗎?無論哪種方式,它仍然需要一些SQL,因爲如果我理解了這個問題,那麼你正在計算一個值。

在傳統的數據庫應用程序中,這將是數據表上的一個視圖。

所以在這種情況下,你可能會做這樣的事情......(注意不是測試或確認它是100%完成)

class Category 
    has_many :entry do 
    def avg_rating() 
     @entries = find :all 
     @entres.each do |en| 
      @value += en.rating 
    end 
    return @value/entries.count 
    end 


end 
+0

但如果你在SQL得到AVG組功能它肯定會更快 – Don

0

編輯 - 檢查EmFi的修訂答案。

我作出任何承諾,但嘗試這個

class Category 
    def average_rating  
    Rating.average :rating, 
     :conditions => [ "type = ? AND entries.category_id = ?", "Entry", id ], 
     :join => "JOIN entries ON rateable_id = entries.id" 
    end 
end