0

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.

0

3 Answers 3

4

It's just the missing bang.

@users.sort! {|a,b| (a.posts.size <=> b.posts.size)}
Sign up to request clarification or add additional context in comments.

Comments

2

You are using sort instead of sort!. sort! will sort @users in place.

Comments

0

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.

1 Comment

I would love to use order or order_by ... but I need to order by the size of a separate query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.