0

I would like to sort forum's users by total_content_length. To get the top n writers in the forum I do:

User.order("total_content_length DESC").limit(n)

Now, the problem is when there are two (or more) users with the same total_content_length. In this case, I would like to give preference to the user that created a post most recently.

Post has publisher_id field (which is a user id).

How would you do this ?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

2 Answers2

1

Try to use 2 order statements:

User.order("total_content_length DESC").order("created_at DESC").limit(n)

Try this:

class User < ActiveRecord::Base
  scope :your_scope_name, joins(:posts).order("posts.created_at DESC")
end

then you can use this scope in conjunction with other statements

bor1s
  • 4,081
  • 18
  • 25
0

Define a method in your User model that gives the date of the latest post (assuming you have a posts association):

def date_of_last_post  
  posts.order('created_at DESC').limit(1)[0].created_at  
end

Then you can get the result as:

top_posters = User.order("total_content_length DESC").limit(n)
# write a conditional sorting algo that swaps values only 
# if a.total_content_length == b.total_content_length based on 'date_of_last_post'
amit_saxena
  • 7,450
  • 5
  • 49
  • 64