【问题标题】::highest_rated scope to order by average rating:highest_rated 范围按平均评分排序
【发布时间】:2011-10-02 06:25:26
【问题描述】:

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

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

但这给了我一个misuse of aggregate: avg() 错误。

关于如何按最高平均评分订购我的产品的任何提示?

【问题讨论】:

    标签: ruby-on-rails scope


    【解决方案1】:

    这行得通:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 2012-05-28
      相关资源
      最近更新 更多