Rails 按 has_many 的聚合选择和排序 [英] Rails select and sort by aggregate of has_many

查看:30
本文介绍了Rails 按 has_many 的聚合选择和排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含_许多评论的课程模型.我的评论模型有一个评级字段.我想要的是查找评分最高的课程的查询.我想在 SQL 中执行此操作,以避免返回所有课程对象,然后尝试对它们进行排名和排序.

I have a Course model which has_many reviews. My Review model has a rating field. What I would like is a query to find the top rated courses. I want to do this in the SQL in order to avoid returning all the course objects and then trying to rank and sort them.

推荐答案

您没有描述如何定义评分最高".可能是您想要个人评分最高的课程:

You don't describe how you define "top rated". It could be that you want the courses with the highest individual ratings:

Course.joins(:reviews).group("courses.id").order("reviews.rating desc")

或者您可能想要总评分最高的课程:

Or you might want the courses with the highest total ratings:

Course.joins(:reviews).group("courses.id").order("sum(reviews.rating) desc")

然后,您可以调用 first(10) 以根据您想要的任何条件获得前十名.

Then on each of these you can call first(10) to get the top ten by whichever criteria you want.

这篇关于Rails 按 has_many 的聚合选择和排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆