title: Rails 5 - How to sort has_many associations list?
body: <p>In rails 5 and in <code>postgresql</code>, I want to sort a list based on <code>created_at: :desc</code>.</p>
  
  <p>Model structure is like,
  models/review.rb</p>
  
  <pre><code>has_many :comments
  has_many :commented_users, :through=&gt;:comments, :source=&gt;:user
  </code></pre>
  
  <p>In views, I want to display list of users based on <code>created_at (DESC)</code> date and this field is from <code>comments</code> table</p>
  
  <p>Controller query is like,</p>
  
  <pre><code>review = Review.find_by_id(params[:id])
  comments = review.commented_users
  </code></pre>
  
  <p>If I give <code>order</code> for <code>review.commented_users</code> then obviously it will sort <code>User</code>, how can I sort users based on <code>Comment</code>?</p>
  
  <p>Review fields are,</p>
  
  <pre><code>=&gt; #&lt;Review id: nil, user_id: nil, content: nil, created_at: nil, updated_at: nil&gt;
  </code></pre>
  
  <p>Comment fields are,</p>
  
  <pre><code>=&gt; #&lt;Comment id: nil, review_id: nil, user_id: nil, created_at: nil, updated_at: nil&gt;
  </code></pre>
  
  <p>User fields are,</p>
  
  <pre><code>=&gt; #&lt;User id: nil, email: "", created_at: nil, updated_at: nil, first_name: nil, last_name: nil, inactive: false, password_updated_at: nil, active: true, reviews_count: 0, notification_seen_at: nil, deleted_at: nil, status: "pending"&gt;
  </code></pre>
  
  <p>Please help me to solve this sorting issue and I am new to <code>postgresql</code></p>