Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Order by the average of an association

I am struggling to add a sorting feature in my fake imdb copycat website.

I have movies that have many reviews through an association. Unfortunately I can't find how to order the @movies object by review average for the index page.

Obviously, this

includes(:reviews).order("reviews.rating_out_of_ten desc")

doesn't work has it only order by the first review of each movie. How can I write it so that it order by the average of all associated reviews ??

Many thanks in advance

like image 309
Fabien Albi Avatar asked Feb 10 '16 09:02

Fabien Albi


1 Answers

In order to sort by the average movie score, join to the reviews table and use the avg function in the order by clause i.e.

Movie
    .select('movie_id, movie_name, avg(reviews.rating_out_of_ten)')
    .join(:reviews)
    .group('movie_id, movie_name')
    .order('avg(reviews.rating_out_of_ten) desc')
like image 96
FuzzyTree Avatar answered Nov 11 '22 10:11

FuzzyTree