ActiveRecord通过多个表中的列进行排序

时间:2018-10-24 01:01:35

标签: ruby-on-rails activerecord

让我说我有一个用户模型

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

并且PostComment都有一个created_at列。

如何根据使用ActiveRecord组合的created_atposts的最新comments列对用户进行排序?

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

1 个答案:

答案 0 :(得分:2)

假设您使用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,代码似乎相同。

相关问题