提问人:itzikos 提问时间:5/8/2018 更新时间:5/8/2018 访问量:117
没有 sql 注入的 ActiveRecord 复杂 where 子句 [duplicate]
ActiveRecord complex where clause without sql injection [duplicate]
问:
我正在为我的网站构建搜索,我正在尝试通过将搜索查询拆分为术语来使用搜索查询,然后按子类别或short_description进行搜索:
whereQuery = ''
declared(params).search.downcase.split(' ').each_with_index do |searchTerm, index|
if index != 0
whereQuery += ' and ';
end
whereQuery += '(lower(short_description) like "%'+searchTerm+'%" or lower(subcategory) like "%'+searchTerm+'%")'
end
orders.where(whereQuery).order(number_of_purchases: :desc, rating: :desc)
有没有更好/更安全的方法来避免此查询的 SQL 注入?
答:
3赞
NARKOZ
5/8/2018
#1
使用 ActiveRecord 链接:
orders = Order
declared(params).search.downcase.split(' ').each do |searchTerm|
orders = orders.where('(LOWER(short_description) LIKE ? OR LOWER(subcategory) LIKE ?', "%#{searchTerm}%", "%#{searchTerm}%")
end
orders = orders.order(number_of_purchases: :desc, rating: :desc)
评论
1赞
Phlip
5/8/2018
你忘记了通配符。编辑你的答案,否则它是迄今为止最好的......%
评论
LIKE ?
.where(whereQuery, *terms)
terms
"%#{searchTerm}%"
AND
LIKE