开发者

Rails parameterized SQL with < >

开发者 https://www.devze.com 2023-03-21 03:59 出处:网络
I have a custom SQL query I want to run, but the user can select < or > from a list drop down开发者_开发问答 of values Before Date and After date respectively.The current SQL in the system for date

I have a custom SQL query I want to run, but the user can select < or > from a list drop down开发者_开发问答 of values Before Date and After date respectively. The current SQL in the system for date looks like this:

searchSQL += " AND a.date_acquired #{params[:asset][:date_range]} '#{params[:asset][:date_acquired]}'"

Where the first one is the < or > sign passed in from the HTML, if I were to sanitize this with

[searchSQL,value1,value2]

at the end, how would I make sure that the < or > could be sanatized without messing up the SQL Query?


Short answer: You can't. At least in the way you're thinking.

Longer answer: You'll have to convert the operator from the select menu into a real sql operator:

def sql_operator_from_param(operation)
  return operation if ['<', '>', '='].include?(operation)
  raise "unknown operation"
end

Then use that in your sql statement in place of the params hash.

A better way, which would avoid decoding string literals would be to assign an index value to your select menu, which you can then use to index into an array of strings that holds the operators .

0

精彩评论

暂无评论...
验证码 换一张
取 消