【问题标题】:How to sort forum's users by "total_content_length" and then by most recent post?如何按“总内容长度”和最近的帖子对论坛用户进行排序?
【发布时间】:2011-05-22 11:32:46
【问题描述】:

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

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

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

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

你会怎么做?

【问题讨论】:

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


    【解决方案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 与其他语句结合使用

    【讨论】:

    • 用户的created_at 与此处无关。它应该以某种方式与Postcreated_at 相关。
    • 这样您就可以为用户创建一些范围,您可以在其中找到他的帖子并通过 created_at 对其进行排序,然后您可以将 .order("created_at DESC") 替换为您的新范围
    • 你会如何为用户编写这个范围?
    • 你可以在范围内使用连接
    • @bor1s:我会感谢更详细的答案:)
    【解决方案2】:

    在你的用户模型中定义一个方法,给出最新帖子的日期(假设你有一个帖子关联):

    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'
    

    【讨论】:

    • 这是不对的,因为当您执行sort! 时,您会“忘记”之前的order 排序...
    • 编辑了我的答案。这不是最好的方法,但可以让你暂时继续前进。您可以使用任何标准排序算法。
    猜你喜欢
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    相关资源
    最近更新 更多