General query using ActiveRecord


#1

Problem: Is the following approach SQL injection safe?

I have five filter fields and would like to be able to ask 2**5 = 32
different WHERE clauses with LIKE conditions.

If it is safe, can it be improved or simplified?

cond = “”
cond += AddCond(“flight like”, “%”, @report.flight, “%”)
cond += AddCond(“description like”, “%”, @report.description, “%”)
cond += AddCond(“users.name http://users.name like”, “%”,
@report.pilot,
“%”)
cond += AddCond(“flightdate >=”, “”, @report.fromdate, “”)
cond += AddCond(“flightdate <=”, “”, @report.todate, “”)

if cond=="" then
@reports = Report.find(:all)
else
@reports = Report.find(:all,
:conditions => “1=1” + cond,
:joins => "INNER JOIN Users ON Reports.user_id = Users.id
http://Users.id
")
end

def AddCond(query, prefix, value, suffix)
if value.nil? then
“”
elsif value == “” then
“”
else
" and " + query + " " + Report.quote(prefix + value + suffix)
end
end