0

我想对论坛的用户进行排序total_content_length。为了获得n论坛中的顶级作家,我这样做:

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

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

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

你会怎么做?

4

2 回答 2

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与其他语句结合使用

于 2011-05-22T11:47:02.687 回答
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'
于 2011-05-22T13:28:09.153 回答