title: Rails query join association table with alias
body: <p>I have a model <code>Edge</code> that belongs to the other model <code>Node</code> twice through different foreign keys:</p>
  
  <pre><code>def Edge &lt; ActiveRecord::Base
      belongs_to :first, class_name: 'Node'
      belongs_to :second, class_name: 'Node'
  end
  </code></pre>
  
  <p>And I want to perform this query using ActiveRecord:</p>
  
  <pre><code>SELECT * FROM edges INNER JOIN nodes as first ON first.id = edges.first_id WHERE first.value = 5
  </code></pre>
  
  <p>I found the way to join association using <code>.joins()</code> method:</p>
  
  <pre><code>Edge.joins(:first)
  </code></pre>
  
  <p>But this produces query using a table name, not an association name, so in <code>.where()</code> method I have to explicitly use table name which breaks association abstraction.</p>
  
  <pre><code>Edge.joins(:first).where(nodes: {value: 5})
  </code></pre>
  
  <p>I can also explicitly use SQL query in <code>.joins()</code> method to define model alias:</p>
  
  <pre><code>Edge.joins('INNER JOIN nodes as first ON nodes.id = edges.first_id')
  </code></pre>
  
  <p>But this breaks even more abstraction.</p>
  
  <p>I think there should be the way to automatically define table alias on join. Or maybe a way to write such function by myself. Something like:</p>
  
  <pre><code>def Edge &lt; ActiveRecord::Base
      ...
      def self.joins_alias
          # Generate something like 
          # joins("INNER JOIN #{relation.table} as #{relation.alias} ON #{relation.alias}.#{relation.primary_key} = #{table}.#{relation.foreign_key}")
      end
  end
  </code></pre>
  
  <p>But I couldn't find any information about accessing information about specific relation like it's name, foreign key, etc. So how can I do it?</p>
  
  <p>Also it seems strange to me that such obvious feature is so complicated even through Rails is on its 4th major version already. Maybe I'm missing something?</p>