In this episode, we're tackling a feature that nearly every forum has: ordering discussions by their latest post. That way, the most recently active threads always float to the top and grab everyone's attention. We start by noticing that our current setup just lists discussions by when they were created, but we really want to order them whenever someone replies to any thread.
To make this magic happen, we create a new scope in our Discussion model called orderByLastPost
. The tricky part is telling our query to look at the timestamp of the last post in each discussion, rather than just the discussion itself. We dig into using a subquery to select the latest created_at
date from the posts related to each discussion, then use that to order all our discussions.
After setting that up, we test things out, tweak a few post times to confirm everything works, and prove that the most recently updated discussions jump to the top as expected. In the end, we see our discussion list now automatically showing the most active conversations first!