title: rails has_many_through creates a double join, how to optimize?
body: <p>I have a situation in which Schools and EventLeg records are tied together through Photos, which belong to a given Event.</p>
  
  <pre><code>class Photo &lt; ActiveRecord::Base
    belongs_to :event
    belongs_to :event_leg
    has_and_belongs_to_many :schools
  end
  class Event &lt; ActiveRecord::Base
    has_many :event_legs, :through =&gt; :photos, :group =&gt; 'event_legs.id'
    has_many :photos
  end
  class School &lt; ActiveRecord::Base
    has_and_belongs_to_many :photos
    has_many :events, :through =&gt; :photos
    has_many :event_legs, :through =&gt; :photos
  end
  class EventLeg &lt; ActiveRecord::Base
    has_many :photos
    has_many :schools, :through =&gt; :photos
  end
  </code></pre>
  
  <p>I need to get the schools that appeared in a given event leg at an event.</p>
  
  <pre><code>@event = Event.find 4088
  @event.schools.joins(:photos).where('photos.event_leg_id' =&gt; 28034)
  </code></pre>
  
  <p>This results in SQL that joins the <code>photos_schools</code> table twice, once to <code>schools</code> and once to <code>photos</code>:</p>
  
  <pre><code>SELECT DISTINCT `schools`.* FROM `schools` 
  INNER JOIN `photos_schools` `photos_schools_join` ON `photos_schools_join`.`school_id` = `schools`.`id` 
  INNER JOIN `photos` `photos_schools_2` ON `photos_schools_2`.`id` = `photos_schools_join`.`photo_id` 
  INNER JOIN `photos_schools` ON `schools`.`id` = `photos_schools`.`school_id` 
  INNER JOIN `photos` ON `photos_schools`.`photo_id` = `photos`.`id` 
  WHERE `photos`.`event_id` = 4088 AND `photos`.`event_leg_id` = 28034
  </code></pre>
  
  <p>The second JOIN of photos_schools -> photos is unnecessary, the following query does the same thing and faster:</p>
  
  <pre><code>SELECT DISTINCT `schools`.* FROM `schools` 
  INNER JOIN `photos_schools` ON `schools`.`id` = `photos_schools`.`school_id` 
  INNER JOIN `photos` ON `photos_schools`.`photo_id` = `photos`.`id` 
  WHERE `photos`.`event_id` = 4088 AND photos.event_leg_id = 28034;
  </code></pre>
  
  <p>So why is AR creating this second set of joins, and how can I make it stop?</p>