我正在更改現有查詢以避免 SQL 注入。查詢是這樣的
People.select('DISTINCT people_id')
.where(person_id: id)
.where("position_id IN (#{approval_id.join(', ')})")
.where('ended_on IS NULL or ended_on > ?', Date.today)
其中approval_id 是值為[1, 2, 3, 4] 的陣列
當我更改查詢第 3 行時
.where("position_id IN (#{approval_id.join(', ')})") to
.where("position_id IN ?", approval_id)
它不作業。出了什么問題?因為approval_id 是一個陣列,我可以將它直接傳遞給IN。
uj5u.com熱心網友回復:
傳入一個陣列,Rails 會將其轉換為一個in查詢。
People
.select('DISTINCT people_id')
.where(
person_id: id,
position_id: approval_id, # approval_ids?
)
.where("ended_on is null or ended_on > ?", Date.today)
nil將被轉換為is null,您可以使用and并將or其完全保存在 ActiveRecord 中。
People
.select('DISTINCT people_id')
.where(
person_id: id,
position_id: approval_id, # approval_ids?
)
.and(
People
.where(ended_on: nil)
.or(People.where(ended_on > ?", Date.today)
)
盡管這在此查詢中可能更復雜,但對其他人了解很有用。
uj5u.com熱心網友回復:
我會使用 Arel 而不是字串:
people_table = People.arel_table
People
.select(:people_id)
.where(person_id: id)
.where(people_table[:position_id].in(approval_id))
.where(
people_table[:ended_on].eq(nil).or(
people_table[:ended_on].gt(Date.today)
)
).distinct
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/446684.html
