Forum: Ruby on Rails General query using ActiveRecord.

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
christer.nilsson (Guest)
on 2005-11-12 23:28
(Received via mailing list)
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
vanek (Guest)
on 2005-11-13 00:28
(Received via mailing list)
Christian Szell: Is it safe?... Is it safe?
     Babe: You're talking to me?
     Christian Szell: Is it safe?
     Babe: Is what safe?
     Christian Szell: Is it safe?
     Babe: I don't know what you mean. I can't tell you something's safe
or not, unless I know specifically
           what you're talking about.
     Christian Szell: Is it safe?
     Babe: Tell me what the "it" refers to.
     Christian Szell: Is it safe?
     Babe: Yes, it's safe, it's very safe, it's so safe you wouldn't
believe it.
     Christian Szell: Is it safe?
     Babe: No. It's not safe, it's... very dangerous, be careful.



Now that I got that out of my system, yes, as long as you call 'quote'
(as you are) you should be fine.


# i would have written it this way
def AddCond(query, prefix, value, suffix)
    return if value.blank?
    " and #{query) #{prefix}#{Report.quote(value)}#{suffix}"
end
christer.nilsson (Guest)
on 2005-11-13 00:40
(Received via mailing list)
Thanks for your answer.
Some corrections were necessary:

  def AddCond(query, prefix, value, suffix)
   return "" if value.blank?
   " and #{query} #{Report.quote(prefix+value+suffix)}"
  end

cheers
This topic is locked and can not be replied to.