title: Avoiding record matching in joins in ActiveRecord
body: <p>I have a <code>Car</code>, <code>Factory</code>, and a <code>Company</code> model. </p>
  
  <pre><code>class Car
   belongs_to :maker, polymorphic: true
  end
  
  class Factory
   has_many :cars, as: :maker
   belongs_to :company
  
   # has a location column
  end
  
  class Company
    has_many :cars, as: :maker
    has_many :factories
  end
  </code></pre>
  
  <p>car has a <code>maker_id</code> column and a <code>maker_type</code> to identify if its <code>Factory</code> or <code>Company</code></p>
  
  <p>Only a factory has a location</p>
  
  <p>I want to get all cars that were made by in a specific location</p>
  
  <p>since some of the cars are made by companies, I need to know what factories they have. </p>
  
  <p>So to put this an example</p>
  
  <blockquote>
    <p>Ferrari has several factories. Any factory that ferrari has can make a
    ferrari car. A local racing team can order a custom car from a nearby
    factory. It could be a Ferrari owned factory, but the car is still
    made by the factory and not by ferrari</p>
  </blockquote>
  
  <p>so, since just factories have a location, everything needs to be around them.
  I need to get the factories around a location, and then get their cars or the company's cars</p>
  
  <pre><code>Car.joins("LEFT OUTER JOIN factories on cars.maker_id = factories.id AND cars.maker_type = 'Factory'")
      .joins("LEFT OUTER JOIN companies ON cars.maker_id = companies.id AND cars.maker_type = 'Company'")
      .merge(Factory.near("Berlin"))
  </code></pre>
  
  <p>this doesn't quite work, as I get no results, I guess because the factories were matched to the companies and weren't a separate table</p>
  
  <p>How can I fix the query so the companies and factories won't be matched to one another? (I don't want to split this into several queries because I am paginating it, ordering, etc)</p>