如何按“total_content_length”排序论坛的用户,然后按最近的帖子排序?

时间:2011-05-22 11:32:46

标签: ruby-on-rails ruby-on-rails-3 activerecord active-relation

我想按total_content_length对论坛的用户进行排序。要在论坛中获得最高n作者:

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

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

Postpublisher_id字段(用户id)。

你会怎么做?

2 个答案:

答案 0 :(得分: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与其他语句结合使用

答案 1 :(得分: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'
相关问题