首页 > 解决方案 > ActiveRecord 按来自多个表的列排序

问题描述

假设我有一个用户模型

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
  ...
end

Post并且两者Comment都有created_at列。

如何根据created_at两者的最新列对用户进行排序postscomments使用 ActiveRecord 组合?

我知道我可以使用 Ruby 的sort方法,但这太慢了。

标签: ruby-on-railsactiverecord

解决方案


假设您使用 PostgreSQL:

# Users with most recently created posts/comments go first
User.left_outer_joins(:posts, :comments)
    .group('users.id')
    .order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')

# .. and go last
User.left_outer_joins(:posts, :comments)
    .group('users.id')
    .order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) ASC')

对于 MySQL,代码似乎是相同的。


推荐阅读