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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With