title: Dynamic direction of ORDER in ActiveRecord query when using a JOIN
body: <p>I'm attempting to cleanup some code that was flagged as being vulnerable to SQL injection. As such, I am converting a lot of raw SQL query strings over to ActiveRecord's methods. One type of query that I'm having an issue finding an equivalent for is when I want to apply ordering (<code>order</code>) to  a nested attribute.</p>
  
  <p>If I have an <code>Account</code> and <code>User</code> object and I wanted to order the result by the <code>user_id</code>, I <em>could</em> do this (this is what the code currently has):</p>
  
  <pre><code>-&gt;(direction) { Account.joins(:users).order("users.id #{direction}").first }
  </code></pre>
  
  <p>However, this is vulnerable to SQL injection. </p>
  
  <p>I know that if I'm ordering by attributes of <code>Account</code>, you can just pass a hash to <code>order</code></p>
  
  <pre><code>-&gt;(direction) { Account.joins(:users).order(created_at: direction).first }
  </code></pre>
  
  <p>However, using a string as the attribute to sort by (since it's nested) doesn't result in the correct query:</p>
  
  <pre><code>-&gt;(direction) { Account.joins(:users).order('users.id': direction).first }
  # SELECT  `accounts`.* FROM `accounts` INNER JOIN `users` ON `users`.`account_id` = `accounts`.`id`  ORDER BY `accounts`.`users.id` DESC LIMIT 1
  </code></pre>
  
  <p>And using a nested hash also doesn't work</p>
  
  <pre><code>-&gt;(direction) { Account.joins(:users).order(users: {id: direction}).first }
  </code></pre>
  
  <p>I know that I can enforce <code>direction</code> to be one of the accepted values with some additional logic, but was wondering if there was an easy way to do this via ActiveRecord's querying that I was missing.</p>