没有sql注入的ActiveRecord复杂where子句
我正在为我的网站建立搜索,我正在尝试使用搜索查询,将其拆分为术语,然后按子类别或简短描述进行搜索:没有sql注入的ActiveRecord复杂where子句,sql,ruby-on-rails,activerecord,sql-injection,Sql,Ruby On Rails,Activerecord,Sql Injection,我正在为我的网站建立搜索,我正在尝试使用搜索查询,将其拆分为术语,然后按子类别或简短描述进行搜索: whereQuery = '' declared(params).search.downcase.split(' ').each_with_index do |searchTerm, index| if index != 0 whereQuery += ' and '; end whereQuery += '(lower(short_description) like "%'+
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注入?使用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)
不确定您的查询,但SQL(所有类型)中应该允许您做的一件事是在where子句中说where 1=1(这样,您就不必检查where子句中是否已经存在某些内容,因为您正在强制它存在某些内容,然后每一条新语句都会放入一些内容和条件。节省大量额外的逻辑,以查看where子句中是否已经存在某些内容,例如SQL中的?,然后是
。where(whereQuery,*terms)
在Ruby代码中,其中术语是带有通配符的字符串数组:“%#{searchTerm}%”
。另外,总是将SQL语句大写是一个非常好的风格规则,例如和以及之类的。这有助于在大量混合语言的情况下提高可读性…您忘记了通配符%
。编辑您的答案,否则这是目前为止最好的。。。