ruby on rails - Sort a resource based on the number of associated resources of other type -


i have movie model has many comments, want sort them (movies) using sql inside active record based on number of associated comments per movie.

how can achieve behavior in efficient way.

i want on fly without counter cache column

you can this

@top_ten_movies = comment.includes(:movie).group(:movie_id).count(:id).sort_by{|k, v| v}.reverse.first(10) 
  • include(:movie) prevent n+1 in sql
  • group(:movie_id) = grouping based on movie each comment
  • sort_by{|k,v|v} = result array of array example [[3,15],[0,10][2,7],...]
  • for first part [3,15] = meaning movie id = 3, has 15 comments
  • you can access array @top_ten_movies[0] = first movie has top comments
  • default ascending, reverse descending comments

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -