ActiveRecord Rails: Query "where" 组合不同的条件

ActiveRecord Rails: Query "where" combine different conditions

我正在做一个搜索过滤器并寻找一种方法来在查询 where 语句中组合不同的条件,如下所示: 查询应显示 (1) 带有符号“AATR”的所有就诊或 (2) 带有符号“ACCT”的所有就诊或 (3) 在 array_ids_scr 中具有筛选 ID 的所有患者或 (4) 具有研究的所有患者array_ids_std 中的 ID。 我知道如何单独编写每个语句,但我不知道如何将它们组合起来。 单独来看应该是

where("visits.symbol = 'AATR' OR visits.symbol = 'ACCT'")
where("patients.scr_id IN (?)", array_ids_scr)
where("patients.std_id IN (?)", array_ids_std)

我尝试按如下方式组合它们,但它没有用(在或接近语法错误)

where("
visits.symbol = 'AATR'
OR
visits.symbol = 'ACCT'
OR
patients.scr_id IN #{array_ids_scr}
OR
patients.std_id IN #{array_ids_std}
")

有办法吗?我正在使用 rails 6.

使用 IN 时,生成的查询应类似于 .. IN (1,2,3)。你在那里的方式看起来像 ...IN [1,2,3]。为此,最好让 ActiveRecord 使用 ?.

处理查询参数

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)

您可以在文档中阅读更多内容,here