2016-04-15 62 views
1

我有一個主題列表,我想按最後發佈的順序顯示所有主題。我認爲當你最近點擊按鈕時,話語會使用類似的東西。如何通過創建帖子的最後一個人來訂購主題?

我試着這樣做

@topics = Topic.includes(:posts).order("posts.created_at desc") 

,但我的主題以一種奇怪的順序得到。

回答

2

我會用scopes只是因爲它很好地概括了搜索功能到類它可以在其他地方重複使用。

class Post < ActiveRecord::Base 
    scope :descending, ->() { order(arel_table[:created_at].desc) } 
end 

class Topic < ActiveRecord::Base 
    # reuse the descending scope from the Post class to define an 
    # order on the Topic class 
    scope :descending, ->() { 
    joins(:posts).merge(Post.descending) 
    } 

end 

然後,你可以這樣做:

@topics = Topic.descending 

如果你也想在查詢職位你仍然可以做:

@topics = Topic.descending.includes(:posts) 
相關問題