class User < AR
has_many :posts
end
class Post < AR
belongs_to :user
end
user2 ; user1
user1
post1 2015-03-01 00:00:00
post2 2015-03-02 00:00:00
user2
post11 2015-03-03 00:00:00
scope :order_list, -> {
select(<<-EOS
users.*,
(SELECT MAX(created_at) FROM posts WHERE users.id = posts.user_id) max_created_at
EOS
).joins(:posts).
order('max_created_at DESC').
uniq
}
虽然使用直接嵌套 SQL 的方法实现了,总觉得应该有更优雅的实现方法,希望各路高手指教一下,谢谢!