我有一个Product和每个产品的has_many ratings。我正在尝试创建一个:highest_rated产品范围,它根据产品的最高平均评级对产品进行排序(每个评级都在ratings表中)。我试过这个:
scope :highest_rated, includes(:ratings).order('avg(ratings.rating) DESC')但这给了我一个misuse of aggregate: avg()错误。
关于如何根据最高平均评分订购我的产品,有什么建议吗?
发布于 2011-07-10 22:41:57
这是可行的:
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')https://stackoverflow.com/questions/6641631
复制相似问题