title: Getting all results from `includes` while filtering the parent model based on included elements?
body: <p>I'm working on a small bug in our app which I'll attempt to simplify here.</p>
  
  <p>I have this company model (the actual model has many more associations, but this here displays the problem):</p>
  
  <pre><code>class Company &lt; ActiveRecord::Base
    has_many :contacts
  
    def self.search(query, page=1)
      companies = includes(:contacts).order("companies.name ASC")
  
      if query.present?
        companies = companies.where(%(
          companies.name ILIKE :q,
          OR contacts.name ILIKE :q
        ), q: "%#{query}%")
      end
  
      companies.paginate(page: page)
    end
  end
  </code></pre>
  
  <p>Now this mostly is working great.  The only problem is when a company has 2 or more contacts, and the user searches based on one of the contact names.  The company is found correctly, and our auto-complete UI displays the company.  HOWEVER, when the user selects the company from the auto-complete they are supposed to be able to select a contact from a dropdown list, but the dropdown ends up only containing the one contact that they had filtered down to.  The company should be filtered based on their search criteria, but that dropdown should still have all of the contacts for the company for the user to choose from.</p>
  
  <p>I know <em>why</em> it's doing this, it's because rails is doing it's auto-load of all of the associations the moment that query runs so that it can both get all association properties <em>and</em> include all conditions at the same time.</p>
  
  <p>It's running a <code>select {every_attribute_from_every_included_table} left outer join {all_included_tables}</code> type of query, but what I WANT it to do is this:</p>
  
  <pre><code>select companies.* from companies
  left outer join contacts &lt;and other included tables&gt; on &lt;join criteria&gt;
  where &lt;filter criteria&gt;
  </code></pre>
  
  <p>To filter the companies followed by a:</p>
  
  <pre><code>select contacts.* from contacts
  where company_id IN (&lt;company_ids from previous query&gt;)
  </code></pre>
  
  <p>Which is how it would include entries normally if the <code>include</code> tables were not also involved in the <code>where</code> clause.</p>
  
  <p>Rails is doing too much magic here and I want it to go back to it's normal magic instead of it's special magic!  How can I do that?  Or what's a better way to accomplish what I'm trying to accomplish (still filter based on contact name, but don't stop those other contacts from being included when I call <code>company.contacts</code>).</p>