title: Rails 4 - how to give alias names to includes() and joins() in active record querying
body: <p>How can I give an alias name for e.g. <code>includes()</code>?
  Following is given: </p>
  
  <ul>
  <li>User: active record model</li>
  <li>Student: active record model, inherits from User (STI)</li>
  <li>Teacher: active record model, inherits from User (STI)</li>
  <li>Project: active record model</li>
  </ul>
  
  <p>Here some examples:</p>
  
  <p><strong>FIRST CASE (more STI associations)</strong></p>
  
  <pre><code>Project.all.includes(:students, :teachers).order('teachers_projects.name ASC') # order on teachers
  Project.all.includes(:students, :teachers).order('users.name ASC') # order on students
  </code></pre>
  
  <p>Rails uses automatically alias name <code>teachers_projects</code> for <code>:teachers</code> in the SQL. How can I overwrite this, so that I can use alias name <code>teachers</code> instead of <code>teachers_projects</code> in the SQL? <code>:students</code> gets alias name <code>users</code>.</p>
  
  <p><strong>This examples fails:</strong></p>
  
  <pre><code>Project.all.includes(:students, :teachers).order('teachers.name ASC')
  Project.all.includes(:students, :teachers).order('students.name ASC')
  Project.all.includes(:students, :teachers).order('students_projects.name ASC')
  </code></pre>
  
  <p><strong>SECOND CASE (one STI association)</strong></p>
  
  <p>If I use only <code>:students</code> (without <code>:teachers</code>) in method <code>includes()</code>, Rails uses name alias of the STI base class name <code>users</code> (without <code>_projects</code> attached) for <code>:students</code>:</p>
  
  <pre><code>Project.all.includes(:students).order('users.name ASC') # order on students
  </code></pre>
  
  <p><strong>This examples fails:</strong></p>
  
  <pre><code>Project.all.includes(:students).order('students.name ASC')
  Project.all.includes(:students).order('students_projects.name ASC')
  </code></pre>
  
  <p><strong>QUESTION</strong></p>
  
  <p>Might exist something like:</p>
  
  <pre><code>Project.all.includes(:students).alias(students: :my_alias)
  </code></pre>
  
  <p><strong>RAILS ALIAS TRACKER</strong></p>
  
  <p><a href="https://github.com/rails/rails/blob/v4.2.0/activerecord/lib/active_record/associations/alias_tracker.rb#L59" rel="noreferrer">https://github.com/rails/rails/blob/v4.2.0/activerecord/lib/active_record/associations/alias_tracker.rb#L59</a></p>
  
  <p><strong>TESTING APP</strong></p>
  
  <p><a href="https://gist.github.com/phlegx/add77d24ebc57f211e8b" rel="noreferrer">https://gist.github.com/phlegx/add77d24ebc57f211e8b</a></p>
  
  <p><a href="https://github.com/phlegx/rails_query_alias_names" rel="noreferrer">https://github.com/phlegx/rails_query_alias_names</a></p>