Hi, all. As someone whose last name has one of those dreaded
apostrophes, I’m acutely aware of how poorly things can go when SQL
queries don’t handle apostrophes correctly. Googling this seems to give
me some indeterminate methods on handling it, and I was wondering if
there’s One True Way to escape strings correctly in Ruby.
first = “T’Luth”
User.where(“first_name LIKE ?”, first) # This is the parameterized call
Matma mentioned.
Under ActiveRecord, the ‘first’ parameter to where() will automatically
be escaped for you.
Under Rails, calling .html_safe will escape non-alphanumeric characters
for you, explicitly, before being passed to the calling method, the
.where() method such as in this example, even though AR will do it for
you, implicitly.
User.where("first_name LIKE ?", "#{first.html_safe}") # Explicit
escaping
The example AR .where() clause is the same regardless if your app is
straight Ruby or Rails. The .html_safe call is a Rails-only method. bear
in mind that you can .html_safe variables directly in an SQL query, but, one still should not get into the habit of directly interpolating
in a query string. Its an unsafe habit to form. (Lord help you if you
forget to call .html_safe and it contains something malicious)
for you, explicitly, before being passed to the calling method, the
in a query string. Its an unsafe habit to form. (Lord help you if you
forget to call .html_safe and it contains something malicious)
Whoa, there. First, html_safe does NOT escape anything or change the
string at all, it marks a string as BEING safe. In other words, you are
explicitly telling Rails NOT to (HTML) escape anything in the string.
Secondly, the HTML escaping in Rails does not escape “non-alphanumeric
characters”, it escapes HTML-specific characters (for latest Rails,
these characters are <,>,&,', and "). So you do not want to HTML-escape
input to a SQL query. Use the ORM’s escaping methods.
Also, while the first example is correct, it is not accurate to say
ActiveRecord will escape the first parameter to where(). The first
parameter is not escaped, the parameters interpolated into the first
parameter with the ? syntax are escaped.
For other safe ways of using ActiveRecord, see the guide:
-Justin
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.