【问题标题】:Rails 3 ActiveRecord Query Interface, Order parents by most recently created child of each parentRails 3 ActiveRecord 查询接口,按每个父级最近创建的子级排序父级
【发布时间】:2011-04-20 16:04:06
【问题描述】:

大家好,我有一个具有_many Posts 的模型线程。

我想知道使用 rails3 如何按降序对线程进行排序,按哪个线程具有最近创建的帖子。

在段/伪代码中这是我想要做的

为每个线程找到最近创建的帖子 以某种方式将该发布日期与其关联的帖子结合起来 按此关联的发布日期升序排列我的主题

【问题讨论】:

    标签: mysql ruby ruby-on-rails-3 activerecord


    【解决方案1】:

    我认为这里最好和最高性能的解决方案是使用touch 选项:

    class Post < ActiveRecord
      belongs_to :thread, :touch => true
    end
    

    因此,您将能够找到最后一个活动线程,如下所示:

    Thread.order("updated_at DESC").limit(10)
    

    查询呢...你可以尝试通过子对象找到它:

    active_threads = Post.includes(:threads).order("created_at DESC").all.map(&:thread).uniq
    

    【讨论】:

      猜你喜欢
      • 2010-11-19
      • 2013-03-25
      • 2013-07-23
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多