2011-09-12 33 views
0

我已經將一堆對象提供給狀態提要,並希望根據他們的最新活動對它們進行排序。如果我只是整理每個對象的created_at屬性的關我將使用代碼:使用自定義方法在rails中排序.sort!

articles = Article.all 
    documents = Document.all 
    @feeds = (articles + documents).sort! { |b, a| a.created_at <=> b.created_at } 

但是,讓我們說,人們可以在文件發佈,使得文件在最新的活動是在最新的created_at屬性帖子。然後我想排序爲這樣:

@feeds = (articles + documents).sort! { |b, a| a.latest_activity <=> b.latest_activity } 

而且我會在模型定義latest_activity:

在Document.rb

def latest_activity 
     self.posts.last.created_at 
end 

在Article.rb

def latest_activity 
    self.created_at 
end 

這不起作用..本地服務器提供以下錯誤:

undefined method `created_at' for nil:NilClass 

我該如何完成這裏所需的排序?

+1

中彈dark--文件與'self.posts.last'是'nil'沒有職位的結果嗎? –

+0

self.posts.last.try(:created_at) – klochner

+0

hmmmm Platinum Azure,幹得好 - 完全忘了爲沒有帖子的文檔添加支票!!! – jay

回答

1

我通常會使用「updated_at」而不是created_at。然後,在您的Post類中:

class Post < ActiveRecord::Base 
    belongs_to :document, :touch => true 
end 

這意味着保存帖子時,它將更新文檔的updated_at列。

然後,以簡化:

articles = Article.all 
documents = Document.all 
@feeds = (articles + documents).sort_by(&:updated_at)