Ruby on Rails order a parent model by child attribute

rails-activerecord, ruby-on-rails

Solution

I would need more information about the layout of your database to give a better example, but you can join another table and then order by that table like so:

Thread.joins(:posts).order("posts.created_at").group("threads.id")

Problem

How would I go about doing this? I would like to sort a selection parent model by an attribute on it's children. The parent model has a has many relationship with it's child. I'm not sure how to form the ActiveRecord query to get this. Example: A thread has many posts. I want to grab a collection of threads ordered by the most recent post associated with it. I've found a few solutions that convert the selection to an array and do a sort on that array, but I need the selection to stay as an ActiveRecord selection, so I can continue to chain queries onto it.

Original source