:按平均评级排序的最高评分范围

我有一个Product ,每个产品都有很多ratings 。 我正在尝试创建一个:highest_rated产品范围,按照最高平均评级对产品进行订购(每个评级都在ratings表中)。 我试过这个:

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

但这让我misuse of aggregate: avg()错误。

有关如何以最高平均评级订购我的产品的任何提示?

这有效:

 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') 

编辑:以上将无法在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')