Safe SQL LIKE conditions in Ruby On Rails
This is a problem that was driving me a little nuts. In this discussion of how to write a Ruby on Rails query without leaving myself open to a SQL Injection, I found this passage:
"Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.first(:conditions => "name LIKE '%#{params[:name]}%'") is not safe. See the next section for the preferred way to handle conditions using an array."However, they never show how to actually write the exact query to replace the unsafe one safely. Here it is:
escaped_query = params[:name].gsub('%', '\%').gsub('_', '\_')
@posts = Post.find(:all, :conditions=> ["subject like :eq or name like :eq", {:eq => "%" + escaped_query + "%"}])