title: JOIN ON ... AND conditions when eager loading association in ActiveRecord
body: <p><strong>Please notice, this is not a question about adding a WHERE condition to an association but a rather advanced question about how to alter the JOIN clause when using eager_load.</strong></p>
  
  <p>Lets say I have these models</p>
  
  <pre><code>class Parent
    has_many :children
    have_many :grades, through: :children
  end
  
  class Child
    belongs_to :parent
  end
  
  class Grade
    belongs_to :child
  end
  </code></pre>
  
  <p>So to eager load the parents I would do:</p>
  
  <pre><code>Parent.eager_load(:grades)
  </code></pre>
  
  <p>But if I wanted all the parents - but only to eager load the highest scoring like so:</p>
  
  <pre><code>LEFT OUTER JOIN grades ON grades.child_id = children.id AND grades.level = 'A+'
  </code></pre>
  
  <p>I have tried using <code>includes(:children).joins("LEFT OUTER JOIN grades ON grades.child_id = children.id AND grades.level = 'A+'")</code> but since Rails does not build the association objects it will cause an extra query for each parent.</p>
  
  <p>I have not found any references on using <code>eager_load</code> with a custom SQL string and have <a href="https://github.com/rails/rails/blob/ad078767fb4d4a78224efaaf541e9bc847cde245/activerecord/lib/active_record/relation/query_methods.rb#L163" rel="nofollow">dug through the source</a> without getting any wiser.</p>