Rails 2+: Sanitize SQL string
Indeed it is sometimes useful to sanitize a query to avoid (most of) SQL injections. Typically, this is the case with your favorite text search field on a website. Obvisouly, you can’t do better than using the Rails standard way of querying, who automatically applies this mechanism. For instance:
MyModel.find(:all,:conditions => ['name LIKE ?','%'+params[:search]+'%'])
But what if you want to create a fragment of a where clause?
This happens in few cases where you create complex queries in different parts of your code.
Well, if you’re in a ActiveRecord model, you can directly call
sanitize_sql_for_conditions(['name LIKE ?','%'+params[:search]+'%']) to output a sql sanitized string.
Easy.
But if you’re in a controller or a custom library, you will surely fall on this
NoMethodError: protected method `sanitize_sql_for_conditions' called for ActiveRecord::Base:Class
Arrrgg!
Well, the answer is quite simple though. Just call the method right inside ActiveRecord:
ActiveRecord::Base.send(:sanitize_sql_for_conditions,['name LIKE ?','%'+params[:search]+'%'])
Hope it helps!