Sorting conversations with belongs_to/has_many relationship <p>i have the following models:</p> <pre><code>class Post &lt; ActiveRecord::Base has_many :conversations end class Conversation &lt; ActiveRecord::Base belongs_to :user belongs_to :post has_many :messages end class Message &lt; ActiveRecord::Base belongs_to :conversation end </code></pre> <p>So there are Posts, and each post can have many conversations. In each conversation are many messages. So far so good.</p> <p>Now i wanna display an overview of all conversations a user has. It seems i can't get it to work the way i want:</p> <p>Get all conversations the current user has (<code>current_user.conversations</code>) group all conversations according to the Post ID they <code>belong_to</code> and rank this groups by date -> The group (of conversations) with the newest message should appear on top. Here is a screenshot of what i have so far. <a href="https://i.stack.imgur.com/SCOaM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SCOaM.png" alt="Sorting conversations"></a></p> <p>All covnerations should be grouped by Posts they belong to at every times. If any conversation has a new message in it, the whole group of conversations should move to the top of the view, not only the conversation with the new message. That's what i can't get to work.</p> <p>The screenshot above was made with the following code:</p> <pre><code>current_user.conversations.includes(:messages, post: :user).order("posts.id DESC, messages.created_at DESC").to_a.paginate( :page =&gt; params[:page], :per_page =&gt; 10 ) </code></pre> <p>As you can see in the screenshot, the conversations are grouped by their post id. But the second group should appear above the first group, because the conversation in the second group has the latest message in it.</p> <p>Any help is appreciated. Thanks a lot!</p>