2009-05-25 85 views
2

我有以下ActiveRecordsActiveRecord的查詢

class Product < ActiveRecord::Base 
    has_many :reviews 
end 

class Review < ActiveRecord::Base 
    belongs_to :product 
end 

每次審查對象包含一個名爲「評級」
場我希望得到的,其平均等級大於規定的約束較大的所有產品的列表。
我不明白如何使用find命令來做到這一點。
是否發現讓我們做這樣的事情?

回答

1

當查詢開始詢問像聚合值這樣的情況時,我會使用SQL。有多種方法可以達到你想要的效果 - 這對我來說是最直接的:

bound = 3 
products = Product.where('id in 
    (
    select product_id 
    from reviews 
    group by product_id 
    having avg(rating) > ?)', bound) 
1

- 是的,它可以做到。像這樣的財產以後應該做的伎倆......

Product.find(:all, :include => 'reviews', :conditions => ['review.rating > ?', min_rating]) 

編輯 - 只要重讀你的問題。你想使用平均評分。我會訴諸SQL來做到這一點,或者如果它是一種常見操作,那麼計算平均評級並在每次保存評級時將其存儲在產品中。