# Sorting forum topics by the most recent replies

**URL:** <https://www.ruby-forum.com/t/sorting-forum-topics-by-the-most-recent-replies/185631>\
**Category:** Rails\
**Created:** [March 23, 2010, 8:58pm UTC](https://www.ruby-forum.com/t/sorting-forum-topics-by-the-most-recent-replies/185631 "2010-03-23T20:58:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![DanC](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/77aa72/32.png) [@DanC](https://www.ruby-forum.com/u/DanC)\
**Post date:** [March 23, 2010, 8:58pm UTC](https://www.ruby-forum.com/t/sorting-forum-topics-by-the-most-recent-replies/185631/1 "2010-03-23T20:58:02Z")

</div>

I have built a simple forum but am having difficult getting the topics  
to display in the order of their latest reply.

The associations are as follows:

class Forum \< ActiveRecord::Base  
has\_many :topics, :order =\> “sticky DESC, created\_at DESC”  
has\_many :replies, :through =\> :topics

class Topic \< ActiveRecord::Base  
belongs\_to :forum  
has\_many :replies, :order =\> “created\_at”, :dependent =\> :destroy

class Reply \< ActiveRecord::Base  
belongs\_to :topic

And in my controller I am calling @topics = @forum.topics

What I would like to do is sort the topics by the created\_at of their  
most recent posts.

Any advice appreciated.

Thanks,

Dan

---

<div class="post-metadata">

**Author:** ![DanC](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/77aa72/32.png) [@DanC](https://www.ruby-forum.com/u/DanC)\
**Post date:** [March 23, 2010, 9:54pm UTC](https://www.ruby-forum.com/t/sorting-forum-topics-by-the-most-recent-replies/185631/2 "2010-03-23T21:54:13Z")

</div>

On 3/23/2010 2:56 PM, DanC wrote:

> belongs\_to :forum  
> Any advice appreciated.

Add a last\_reply\_at field to Topic. Add a after\_save to Reply that  
updates last\_reply\_at. When you find all topics sort by last\_reply\_at.

> Thanks,
> 
> Dan

–  
Jack C.  
removed\_email\_address@domain.invalid
