try this, not sure if it's completely right. Hope it's helpful to you.
User.joins(recipes: [:comments]).group('users.id').order('AVG(comments.rating) DESC')
update
my Models are User, Quiz, Question. The part confusing me a lot is your definition of User. Are the users who posted courses, and the users who comment in the same table or separate table? The relationship I mocked is this, which is I think is almost exactly same as your models:
- User has_many quizzes, and user has_many questions.
- Quiz has_many questions, and belongs_to user.
- Questions belongs_to a user, and belongs_to a quizz.
in this case, if I do @users = User.joins(quizzes: [:questions]).group('users.id').order('AVG(questions.easy_count) DESC')
, the result I get is, the result @users
is a list of user who owns quizzes ordered by the easy_count(in your case rating) questions belongs to the corresponding quiz.
explanation of the code
User.joins(quizzes: [:questions])
simple gives you all rows of users who has quizzes(in your case should be courses) which has questions(in your case should be comment). consider the below example:
- user1 has quiz1
- quiz1 has question1 and question2
the result you get from User.joins(quizzes: [:questions])
will return you two duplicated rows of user1(because user1 is related to two questions through quiz1)
then group('users.id')
is going to group the result from User.joins(quizzes: [:questions])
by user.id
(you want to get user list)
so so far, what you get is very simple, it's a list of users who has quizzes and those quizzes need to have at least one question, I'm pretty sure it is the owner user of the quiz, not the owner user of the questions.
then at the end you sort this list by average easy_count of questions(in your case, rating of comments)