0

我想用total_content_length来分类论坛用户。让高层n作家在论坛上,我做的:现在如何根据“total_content_length”和最近的帖子对论坛用户进行排序?

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

,问题是当有两个(或更多)用户使用同一total_content_length。 在这种情况下,我想优先考虑最近创建帖子的用户。

Postpublisher_id字段(这是一个用户id)。

你会如何做到这一点?

回答

1

尝试使用2点阶声明:

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

试试这个:

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

,那么你可以结合使用此scope与其他报表

+0

用户'created_at'是不是与此有关。它应该以某种方式与'Post'的'created_at'相关。 – 2011-05-22 11:55:46

+0

所以你可以为用户创建一些范围,你可以在其中找到他的帖子并通过created_at来订购它们,然后你可以用你的新范围替换.order(“created_at DESC”) – bor1s 2011-05-22 12:07:27

+0

你会如何为用户编写这个范围? – 2011-05-22 13:04:58

0

定义的方法在你的提供最新帖子日期的用户模型(假设您有帖子关联):

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

然后你就可以得到结果为:

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

这是不对的,因为当您执行'sort!'时,您忘记了以前的'order'排序... – 2011-05-22 13:57:14

+0

已编辑我的答案这不是最好的方法,但可以让你暂时去,你可以使用任何标准的排序算法。 – 2011-05-22 15:28:11

相关问题