gpt4 book ai didi

ruby-on-rails - :highest_rated scope to order by average rating

转载 作者:行者123 更新时间:2023-12-04 06:14:50 24 4
gpt4 key购买 nike

我有一个Product,每个产品都有_many ratings。我正在尝试创建一个 :highest_rated Product 范围,它按产品的最高平均评级对产品进行排序(每个评级都在 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')

关于ruby-on-rails - :highest_rated scope to order by average rating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6641631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com