2011-11-30 33 views
1

我有一個模型用戶與相關類(用戶has_many帖子,帖子belongs_to用戶)。我想在列表中顯示用戶,以及最近發佈在頂部的用戶。所以基本上我想通過他們上一篇文章的created_at日期來訂購用戶列表。在Rails 3中查詢這個最好的方法是什麼?由Rails中的相關類created_at排序

謝謝!

回答

1

也許嘗試這樣的事情。

class User < ActiveRecord::Base 
    has_many :posts 

    has_one :last_post, :order => 'created_at DESC', :class_name => "Post" 

    scope :sort_by_last_post_desc, :include => :last_post, :order => ('posts.created_at DESC') 
end 

注:未測試

2

我想我會通過拉動帖子,通過created_at排序,並通過在user_id上進行分組來完成此操作。