title: How do I order by foreign attribute for belongs_to reference where there are 2 keys to foreign table
body: <p>I have a Model which has a <code>belongs_to</code> association with another Model as follows</p>
  
  <pre><code>class Article
    belongs_to :author, :class_name =&gt; "User"
  end
  </code></pre>
  
  <p>If I wanted to find all articles for a particular genre ordered by author I would do something like the following</p>
  
  <pre><code>articles = Article.all(:includes =&gt; [:author], :order =&gt; "users.name")
  </code></pre>
  
  <p>However if <code>Article</code> happens to have two references to <code>User</code> how can I sort on <code>:author</code>?</p>
  
  <pre><code>class Article
    belongs_to :editor, :class_name =&gt; "User"
    belongs_to :author, :class_name =&gt; "User"
  end
  </code></pre>
  
  <p>I have tried</p>
  
  <pre><code>articles = Article.all(:includes =&gt; [:author], :order =&gt; "users.name") 
  #=&gt; incorrect results
  articles = Article.all(:includes =&gt; [:author], :order =&gt; "authors.name") 
  #=&gt; Exception Thrown
  </code></pre>
  
  <h2> My first attempted solution </h2>
  
  <p>A half solution is as follows. It was not totally obvious but looking at my logs I figured it out.</p>
  
  <pre><code>class Article
    belongs_to :editor, :class_name =&gt; "User"
    belongs_to :author, :class_name =&gt; "User"
  end
  </code></pre>
  
  <p>Basically you need to do the following</p>
  
  <p><strike><code>articles = Article.all(:include => [:editor,:author], :order => 'articles_authors.name')</code></strike></p>
  
  <pre><code>articles = Article.all(:include =&gt; [:editor,:author], :order =&gt; 'authors_articles.name') 
  </code></pre>
  
  <p>It is the naming of the alias that I missed (articles_authors)</p>
  
  <p>The issue with this is that the following does not work although it seems like it should.</p>
  
  <p><strike><code>articles = Article.all(:include => [:editor,:author], :order => 'authors_articles.name')</code></strike></p>
  
  <pre><code>articles = Article.all(:include =&gt; [:editor,:author], :order =&gt; 'editors_articles.name')
  </code></pre>
  
  <p>This may be an issue if you have a UI table and want to send the order field to the controller. So you may want to first order on author then editor. But it would fail for for one of the queries (unless you dynamically change the include too)</p>