2011-07-10 11 views
3

私にはProduct、各商品にはratingsがあります。私は:highest_rated製品の範囲を作成しようとしています。最高の平均評価で製品を注文しています(それぞれの評価はratingsの表にあります)。私はこれを試みた::highest_rated平均レーティングで注文する範囲

scope :highest_rated, includes(:ratings).order('avg(ratings.rating) DESC') 

しかしそれは私にmisuse of aggregate: avg()エラーを与えた。

私の製品は平均して最高の評価を得るためのヒントを教えてください。

答えて

5

これは動作します:

scope :highest_rated, includes(:ratings).group('product_id').order('AVG(ratings.rating) DESC') 

をのみ、既存の評価と製品を取得するために:

scope :highest_rated, includes(:ratings).group('product_id').where('ratings.rating IS NOT NULL').order('AVG(ratings.rating) DESC') 

EDIT:上記のPostgreSQLでは動作しません。代わりにこれを使用しました(SQLiteとPostgreSQLの両方で動作します)。

scope :highest_rated, where("products.id in (select product_id from ratings)").group('products.id, products.name, products.all_other_fields').joins(:ratings).order('AVG(ratings.rating) DESC')