Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely escape strings for SQL fragments for joins, limits, selects, and so on (not conditions) on Rails

In Ruby on Rails, for conditions, it's easy to make SQL-injection-proof queries:

:conditions => ["title = ?", title]

where title comes from the outside, from a web form or something like that.

But what if you are using SQL fragments in other parts of the query, like:

:select => "\"#{title}\" AS title"   # I do have something like this in one instance
:joins => ["LEFT JOIN blah AS blah2 ON blah2.title = \"#{title}\""]

Is there a way to properly escape those strings?

like image 743
pupeno Avatar asked Nov 12 '09 16:11

pupeno


1 Answers

Typically in Rails, joins are done as a symbol (or as a hash for second-order joins) representing an id join, and you use the conditions to filter it down. If you need to do it as shown, then you can use ActiveRecord's sanitize_sql_array to clean a SQL string, like this:

sanitize_sql_array(["LEFT JOIN blah AS blah2 ON blah2.title = ?", @blah.title])
like image 96
Andrew Vit Avatar answered Nov 18 '22 13:11

Andrew Vit