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 =开发者_如何学Python> "\"#{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?
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])
精彩评论