'Where' 和 'IN' in ruby on rails 以避免 SQL 注入
'Where' and 'IN' in ruby on rails to avoid SQL injection
我正在更改现有查询以避免 SQL injection.The 查询像这样
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。
Pass in an array and Rails will convert it to an in
query.
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
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)
)
虽然这在这个查询中可以说更复杂,但了解它对其他人很有用。
我会使用 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
我正在更改现有查询以避免 SQL injection.The 查询像这样
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。
Pass in an array and Rails will convert it to an in
query.
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
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)
)
虽然这在这个查询中可以说更复杂,但了解它对其他人很有用。
我会使用 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