title: Rails includes associations with left join conditions
body: <p>Consider these two associated models, <code>Program</code> and <code>SpentFinance</code>:</p>
  
  <pre><code>class Program &lt; ApplicationRecord
    has_many :spent_finances
  end
  
  class SpentFinance &lt; ApplicationRecord
  end
  </code></pre>
  
  <p>Each spent finance has a <code>time_period_type</code>, such as <code>'year'</code> or <code>'month'</code>.</p>
  
  <p>How can I retrieve all programs, and at the same time preload all associated <code>spent_finances</code> associated with a program that have a certain <code>time_period_type</code>?</p>
  
  <p>Note:</p>
  
  <ul>
  <li>The query must retrieve ALL programs, including programs that do not have any spent finances of the requested time period type.</li>
  <li>Should provide a way to programmatically change the <code>time_period_type</code> in the query</li>
  </ul>
  
  <hr>
  
  <p>These are the attempts I've made at cracking this problem.</p>
  
  <p><strong>First attempt</strong></p>
  
  <pre><code>Program
  .references(:spent_finances)
  .includes(:spent_finances)
  .merge(SpentFinance.where(time_period_type: time_period_type))
  </code></pre>
  
  <p>This doesn't work, because it filters out programs that don't have spent finances with the specified time period type. (It adds the time_period_type condition to the WHERE clause and not the JOIN ON clause.)</p>
  
  <p><strong>Second attempt</strong></p>
  
  <pre><code>class Program &lt; ApplicationRecord
    has_many :yearly_spent_finances,
      -&gt; { where(time_period_type: 'year') },
      className: 'SpentFinance'
  end
  
  programs = Program.references(:yearly_spent_finances).includes(:yearly_spent_finances)
  
  programs[0].yearly_spent_finances
  </code></pre>
  
  <p>This works (the last line does not execute another query), and indeed it is the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Eager+loading+of+associations" rel="nofollow noreferrer">officially recommended solution</a>. However, it doesn't allow me to programmatically specify the desired <code>time_period_type</code>. For example, if I want to do a similar query as above, but change the time_period_type to <code>'month'</code>, then I would have to add another association <code>has_many :monthly_spent_finances</code>.</p>