问题
I need to filter according to key + value in a polymorphic association. In this example, an Incident
can have many CustomFieldsValues
, and I need to filter Incidents
by CustomFieldsValue.custom_field_id
and CustomFieldsValue.value
.
I tried creating a search like the following SQL query:
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 >= '2015-06-29 10:00:00') AND (custom_fields_values.value <= '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'))
);
Or this one with LEFT OUTER JOIN
:
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 >= '2015-06-29 10:00:00') AND (custom_fields_values.value <= '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'))
);
I thought the Ransack query would look something like this:
Incident.ransack(:m=>"and", :g=>{
"0"=>{"id_in"=>{
"0"=>{:m=>"and", :g=>{
"0"=>{"custom_fields_values_custom_field_id_is"=>1091},
"1"=>{"custom_fields_values_value_gte_any"=>["2015-06-29 00:00:00"]},
"2"=>{"custom_fields_values_value_lte_any"=>["2015-07-02 23:59:59"]}
}}}},
"1"=>{"id_in"=>{
"0"=>{:m=>"and", :g=>{
"0"=>{"custom_fields_values_custom_field_id_is"=>1099},
"1"=>{"custom_fields_values_value_is_any"=>["bbb"]}
}}}}
})
Is there a way to include nested queries in Ransack? I tried merging searches, but got NoMethodError: undefined method 'base' for #<CustomFieldsValue::ActiveRecord_Relation:0x0000010fc45eb8>
.
Is there another way of doing this?
来源:https://stackoverflow.com/questions/31432074/ransack-how-to-merge-sub-queries