在自定义条件下清理SQL

时间:2009-07-17 14:30:10

标签: sql ruby-on-rails sanitize

我需要创建一个简单的搜索,但我不能使用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不起作用!它返回只返回原始字符串。

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我在ActiveRecord中使用了很多自定义条件,但是我喜欢将它们打包在条件数组的数组中,然后将它们组合起来,使用?值让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