Eri*_*ang 3 scope ruby-on-rails
我有一个Product和每个产品has_many ratings.我正在尝试创建一个:highest_rated产品范围,按照最高平均评级对产品进行订购(每个评级都在ratings表中).我试过这个:
scope :highest_rated, includes(:ratings).order('avg(ratings.rating) DESC')
Run Code Online (Sandbox Code Playgroud)
但这给了我一个misuse of aggregate: avg()错误.
有关如何以最高平均评级订购我的产品的任何提示?
这有效:
scope :highest_rated, includes(:ratings).group('product_id').order('AVG(ratings.rating) DESC')
Run Code Online (Sandbox Code Playgroud)
仅获取具有现有评级的产品:
scope :highest_rated, includes(:ratings).group('product_id').where('ratings.rating IS NOT NULL').order('AVG(ratings.rating) DESC')
Run Code Online (Sandbox Code Playgroud)
编辑:上面的内容在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')
Run Code Online (Sandbox Code Playgroud)