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