title: ActiveRecord Subquery Inner Join
body: <p>I am trying to convert a "raw" PostGIS SQL query into a Rails ActiveRecord query. My goal is to convert two sequential ActiveRecord queries (each taking ~1ms) into a single ActiveRecord query taking (~1ms). Using the SQL below with <code>ActiveRecord::Base.connection.execute</code> I was able to validate the reduction in time.</p>
  
  <p>Thus, my direct request is to help me to convert this query into an ActiveRecord query (and the best way to execute it).</p>
  
  <pre><code>SELECT COUNT(*)
  FROM "users"
  INNER JOIN (
    SELECT "centroid"
    FROM "zip_caches"
    WHERE "zip_caches"."postalcode" = '&lt;postalcode&gt;'
  ) AS "sub" ON ST_Intersects("users"."vendor_coverage", "sub"."centroid")
  WHERE "users"."active" = 1;
  </code></pre>
  
  <p><strong>NOTE</strong> that the value <code>&lt;postalcode&gt;</code> is the only variable data in this query. Obviously, there are two models here <code>User</code> and <code>ZipCache</code>. <code>User</code> has no direct relation to <code>ZipCache</code>.</p>
  
  <p>The current two step ActiveRecord query looks like this.</p>
  
  <pre><code>zip = ZipCache.select(:centroid).where(postalcode: '&lt;postalcode&gt;').limit(1).first
  User.where{st_intersects(vendor_coverage, zip.centroid)}.count
  </code></pre>