2011-11-02 155 views
0

我找我的所有聯繫人,並通過使用這種(工作正常),包括相關的注意事項資源:排序包含按日期

@contact = Contact.find(params[:id], :include => :notes) 

不過,我想通過created_at日期,如何將包含筆記整理我可以做到這一點嗎?

感謝, 約翰

+2

你嘗試只需添加':爲了=>:created_at'到'的has_many:在接觸模型notes'線,或將這項突破別的東西嗎? – Frost

+0

謝謝,我使用了「has_many:notes,:order =>'created_at DESC'」並且工作正常。 – John

回答

0

無論是:order條款添加到您的has_many聲明馬丁建議,或將其添加到查詢,在這裏你可能必須指定表名,以避免歧義。在Rails 3.x的語法:

Contact.includes(:notes).find(params[:id]).order("notes.created_at DESC") 
+0

我不相信這會工作...'Contact.find(id)'將是一個聯繫對象,而不是一個關係,所以它沒有包含方法,或者如果它,它不會做你想要什麼。使用'Contact.where(:id => params(:id)'而不是Contact.find不會失敗,但我不知道你可以用這種方法對包含的對象進行排序。 – MrTheWalrus

+0

你是對的,修復鏈接訂單 – Thilo

+0

我相信只要.find出現在.order之前,它就會失敗,因爲Contact沒有'order'方法比'include'更多。 – MrTheWalrus