title: Wrong sql generated by ActiveRecord for has_many :through relation with STI
body: <p>Consider these models:</p>
  
  <pre><code>class First &lt; ActiveRecord::Base
    has_many :tags
    has_many :thirds, :through =&gt; :tags
  end
  
  class Second &lt; ActiveRecord::Base
  end
  
  class Third &lt; Second
    has_many :tags
    has_many :firsts, :through =&gt; :tags
  end
  
  class Tag &lt; ActiveRecord::Base
    belongs_to :first
    belongs_to :third
  end
  </code></pre>
  
  <p>In other words, we have a has_many :through 'tag-style' relationship, but with one of the models (Third) being an STI inheriting from another (Second).</p>
  
  <p>Say I wanted to do a join to see all instances of Third for some value of First:</p>
  
  <pre><code>@thirds = Third.joins(:firsts).where("first.id = 2")
  </code></pre>
  
  <p>This will work as expected; the generated sql (via to_sql) being:</p>
  
  <pre><code>SELECT `seconds`.* FROM `seconds`
  INNER JOIN `tags` ON `seconds`.`id` = `tags`.`third_id`
  INNER JOIN `firsts` ON `firsts`.`id` = `tags`.`first_id`
  WHERE `seconds`.`type` = 'Third' AND (first.id = 1)
  </code></pre>
  
  <p>This doesn't work in the other direction:</p>
  
  <pre><code>@firsts = First.joins(:thirds).where("second.id = 2")
  </code></pre>
  
  <p>The SQL generated being:</p>
  
  <pre><code>SELECT `firsts`.* FROM `firsts` 
  INNER JOIN `tags` ON `firsts`.`id` = `tags`.`first_id` 
  INNER JOIN `seconds` ON `seconds`.`type` = 'Third'
  WHERE (second.id = 2)
  </code></pre>
  
  <p>This results in tag duplication due to the fact that :seconds are not joined correctly with the tag table as in the first case above (see third line of sql statement in each case). All firsts with tags will show up in the resulting table, the WHERE clause being entirely ineffectual.</p>
  
  <p>If something else needs to be specified, I have not come across it. If anybody knows how to force this to work, please let me know. Otherwise, I'm assuming this is a bug in Rails. Oh, and please don't suggest I use the old model.find() methods which are due to be deprecated.</p>
  
  <p>UPDATE:</p>
  
  <p><a href="https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/6608-generated-sql-for-has_many-through-relation-wrong-when-used-with-sti" rel="nofollow">https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/6608-generated-sql-for-has_many-through-relation-wrong-when-used-with-sti</a></p>
  
  <p>So according to the guy who confirmed this was a bug, 'if you define the association in the base class it works as expected though.'
  Does anyone know what that means/how to do this?</p>