ActiveRecord复杂where子句没有sql注入

时间:2018-05-07 18:11:31

标签: sql ruby-on-rails activerecord sql-injection

我正在构建对我的网站的搜索,我尝试使用搜索查询将其拆分为术语,然后按子类别或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 INJECTION?

1 个答案:

答案 0 :(得分:2)

使用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)