I'm trying to sort the array @users by the number of posts they have. Here's what I have in my controller:
@users = User.includes([:posts]).where("user_type = ?", "A")
@users.sort {|a,b| (a.posts.size <=> b.posts.size)}
Here's what I have in my view:
<% @users.each do |user| %>
<%= user.name %>: <%= user.posts.size %>
<br>
<% end %>
My list of users is pretty random and is not properly sorted. If I'm not mistaken, the <=> operator is what I want to use. I want to return 1 if a has more posts than b, -1 if b has more posts than a and 0 if a and b have the same number of posts.