I am doing a search filter and looking for a method to combine different conditions in a query where statement as following: the query should show either (1) all visits with symbol "AATR" or (2) all visits with symbol "ACCT" or (3) all patients with screening id in an array_ids_scr or (4) all patients with study id in an array_ids_std. I know how to write each statement individually but i do not know how to combine them. Individually, it should be
where("visits.symbol = 'AATR' OR visits.symbol = 'ACCT'")
where("patients.scr_id IN (?)", array_ids_scr)
where("patients.std_id IN (?)", array_ids_std)
I tried to combine them as following but it did not work (syntax error at or near)
where("
visits.symbol = 'AATR'
OR
visits.symbol = 'ACCT'
OR
patients.scr_id IN #{array_ids_scr}
OR
patients.std_id IN #{array_ids_std}
")
Is there a way to do that? I am using rails 6.
CodePudding user response:
When working with IN
the resulting query should look like .. IN (1,2,3)
. The way you have it there it looks like ...IN [1,2,3]
. For this it's best to leave ActiveRecord handle the query params by using ?
.
Active Record will take the first argument as the conditions string and any additional arguments will replace the question marks (?) in it.
where("
visits.symbol = 'AATR' OR
visits.symbol = 'ACCT' OR
patients.scr_id IN (?) OR
patients.std_id IN (?)", array_ids_scr, array_ids_std)
You can read more in the docs, here