title: Ransack: how to merge sub-queries?
body: <p>I need to filter according to key + value in a polymorphic association. In this example, an <code>Incident</code> can have many <code>CustomFieldsValues</code>, and I need to filter <code>Incidents</code> by <code>CustomFieldsValue.custom_field_id</code> and <code>CustomFieldsValue.value</code>.</p>
  
  <p>I tried creating a search like the following SQL query:</p>
  
  <pre><code>SELECT id FROM incidents
  WHERE id IN (
    SELECT customfieldable_id from custom_fields_values
    WHERE (custom_fields_values.custom_field_id = 1091 AND (custom_fields_values.value &gt;= '2015-06-29 10:00:00') AND (custom_fields_values.value &lt;= '2015-07-03 09:59:59'))
  )
  AND id IN (
    SELECT customfieldable_id from custom_fields_values
    WHERE (custom_fields_values.custom_field_id = 1099 AND (custom_fields_values.value = 'bbb'))
  );
  </code></pre>
  
  <p>Or this one with <code>LEFT OUTER JOIN</code>:</p>
  
  <pre><code>SELECT distinct incidents.id FROM incidents
  LEFT OUTER JOIN custom_fields_values ON custom_fields_values.customfieldable_id = incidents.id AND custom_fields_values.customfieldable_type = 'Incident'
  WHERE incidents.id IN (
    SELECT customfieldable_id from custom_fields_values
    WHERE (custom_fields_values.custom_field_id = 1091 AND (custom_fields_values.value &gt;= '2015-06-29 10:00:00') AND (custom_fields_values.value &lt;= '2015-07-03 09:59:59'))
  )
  AND incidents.id IN (
    SELECT customfieldable_id from custom_fields_values
    WHERE (custom_fields_values.custom_field_id = 1099 AND (custom_fields_values.value = 'bbb'))
  );
  </code></pre>
  
  <p>I thought the Ransack query would look something like this:</p>
  
  <pre><code>Incident.ransack(:m=&gt;"and", :g=&gt;{
    "0"=&gt;{"id_in"=&gt;{
      "0"=&gt;{:m=&gt;"and", :g=&gt;{
        "0"=&gt;{"custom_fields_values_custom_field_id_is"=&gt;1091},
        "1"=&gt;{"custom_fields_values_value_gte_any"=&gt;["2015-06-29 00:00:00"]},
        "2"=&gt;{"custom_fields_values_value_lte_any"=&gt;["2015-07-02 23:59:59"]}
      }}}},
    "1"=&gt;{"id_in"=&gt;{
      "0"=&gt;{:m=&gt;"and", :g=&gt;{
        "0"=&gt;{"custom_fields_values_custom_field_id_is"=&gt;1099},
        "1"=&gt;{"custom_fields_values_value_is_any"=&gt;["bbb"]}
    }}}}
  })
  </code></pre>
  
  <p>Is there a way to include nested queries in Ransack? I tried <a href="https://github.com/activerecord-hackery/ransack/wiki/Merging-Searches" rel="nofollow">merging searches</a>, but got <code>NoMethodError: undefined method 'base' for #&lt;CustomFieldsValue::ActiveRecord_Relation:0x0000010fc45eb8&gt;</code>.</p>
  
  <p>Is there another way of doing this?</p>