Sorting a collection by up vote counts

I have a Question model and each question can be voted up by the users. And I want to display them in the decreasing order of their votes.

I have this

<%= render partial: ‘questions/question’, collection: @questions.sort!{|a,b| a.votes.up.count <=> b.votes.up.count}.reverse! %>

Now which is the best way to refactor this? Is it possible to put this in the Question model itself using scope which by default returns me all the questions in a sorted manner. Or do I need to put that sorting logic in a helper method?

Also how I can test that always the questions are returned to me in that order?

In general, yes – you should probably:

  • Move counting and sorting to the model
  • Use the controller to setup a @questions collection which is already sorted instead of doing it in the view

You could use the Rails counter cache to store the number of votes directly on each Question, and then either add a scope to Question or use Rails built-in order method.

1 Like