The issue arose when I wanted to find patients who satisfy both of the following conditions. When I put the query into Ransack like this:
queries = {"groupings" => {
"0" => {
"c" => {
"0" => {
"a" => { "0" => { "name" => "disease_code" } },
"p" => "eq",
"v" => { "0" => { "value" => "1234" } }
},
"1" => {
"a" => { "0" => { "name" => "disease_type" } },
"p" => "in",
"v" => { "0" => { "value" => "1" } }
},
"2" => {
"a" => { "0" => { "name" => "disease_code" } },
"p" => "eq",
"v" => { "0" => { "value" => "4567" } }
},
"3" => {
"a" => { "0" => { "name" => "flag" } },
"p" => "in",
"v" => { "0" => { "value" => "1" } }
},
}
}
}
patient.ransack(queries).result.to_sql
This is what gets returned:
select *
from patients p
join patient_diseases pd
on p.id = pd.patient_id
where pd.disease_code in 1234
and pd.disease_type = 1
and pd.disease_code in (4567)
and pd.flag in (1)
but I want SQL like this
select *
from patients p
join patient_diseases pd1
on p.id = pd1.patient_id
where pd1.disease_code = 1234
and pd1.disease_type = 1
and exists (
select 1
from patient_diseases pd2
where pd2.patient_id = p.id
and pd2.disease_code = 4567
and pd2.flag = 1
);
Instead, I am considering fetching the results for each condition separately and then finding the intersection of these results in the backend.
For example, I have a Patient model and I want to find patients that satisfy condition_1 and condition_2.
# Patients satisfying condition_1
patients_condition_1 = Patient.where(condition_1)
# Patients satisfying condition_2
patients_condition_2 = Patient.where(condition_2)
# Intersection of both conditions
intersecting_patients = patients_condition_1 & patients_condition_2
Is this a good approach, or is there a better way to achieve this in Rails? Any suggestions or improvements are highly appreciated!
PS: I know I could subquery but, there is so many different condition to find it.
So, I give up using a subquery.
0 comments:
Post a Comment
Thanks