Reputation: 2444
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.
Upvotes: 0
Views: 58
Reputation: 160553
Two things I see:
Instead of using sort
, use sort_by
when you have to dig into an object. It shouldn't be a big speed up for the short method chain you're using, but it can add up:
@users.sort_by! {|a| a.posts.size }
If you're retrieving your data from the database, instead of sorting in Ruby, use order
or order_by
, depending on which is supported, to have the DBM sort the data in the order you want. DBMs are optimized for sorting and can do it extremely fast.
Upvotes: 0
Reputation: 29860
You are using sort
instead of sort!
. sort!
will sort @users
in place.
Upvotes: 2
Reputation: 16012
It's just the missing bang.
@users.sort! {|a,b| (a.posts.size <=> b.posts.size)}
Upvotes: 4