开发者

How to sort forum's users by "total_content_length" and then by most recent post?

开发者 https://www.devze.com 2023-03-07 19:33 出处:网络
I would like to sort forum\'s users by total_content_length. To get the top n writers in the forum I do:

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 ?


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


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'
0

精彩评论

暂无评论...
验证码 换一张
取 消