2

我需要创建一个简单的搜索,但我负担不起使用 Sphinx。

这是我写的:


keywords = input.split(/\s+/)
queries = []

keywords.each do |keyword|
  queries << sanitize_sql_for_conditions(
              "(classifications.species LIKE '%#{keyword}%' OR 
               classifications.family LIKE '%#{keyword}%' OR 
               classifications.trivial_names LIKE '%#{keyword}%' OR
               place LIKE '%#{keyword}%')")
end

options[:conditions] = queries.join(' AND ')

现在,sanitize_sql_for_conditions 不起作用!它返回只是返回原始字符串。

如何重写此代码以逃避恶意代码?

4

2 回答 2

9

如果您将“#{keyword}”替换为“?”,您可以执行以下操作。使用问号将自动清理 SQL。

keywords = input.split(/\s+/)
queries = []
vars = []

keywords.each do |keyword|
  queries << "(classifications.species LIKE '%?%' OR 
               classifications.family LIKE '%?%' OR 
               classifications.trivial_names LIKE '%?%' OR
               place LIKE '%?%')"
  vars = vars << keyword << keyword << keyword << keyword
end

options[:conditions] = [queries.join(' AND '), vars].flatten
于 2009-07-17T14:43:13.373 回答
0

我在 ActiveRecord 中使用了很多自定义条件,但我喜欢将它们打包到条件数组的数组中,然后使用 ? value 让 AR 自动清理它们:

conditions = Array.new
conditions << ["name = ?", "bob"]
conditions << ["(created_at > ? and created_at < ?)", 1.year.ago, 1.year.from_now]  

User.find(:first, :conditions => combine_conditions(conditions))

 def combine_conditions(somearray) # takes an array of condition set arrays and reform them into a AR-compatible condition array
   conditions = Array.new
   values = Array.new
   somearray.each do |conditions_array|
     conditions << conditions_array[0] # place the condition in an array
     # extract values
     for i in (1..conditions_array.size - 1)
       values << conditions_array[i]
     end 
   end
   [conditions.join(" AND "), values].flatten
 end
于 2010-12-13T20:33:37.177 回答