High Tech Sorcery

2 ways to use LIKE queries with wildcards safely in Rails finders

by on Feb.11, 2010, under Ruby On Rails

It is important to sanitize variables that may come from users to prevent SQL injection attacks.  Rails makes this easy by default:

Author.find(:all, :conditions=>['first_name = ?', first_name]

However this will not work:
Author.find(:all, :conditions=>['first_name LIKE "%?%"', first_name]

This will work but is  insecure:
Author.find(:all, :conditions=>"first_name LIKE '%#{first_name}%'"

Solution 1:
Author.find(:all, :conditions=>['first_name LIKE ?', "%#{first_name}%"]

Solution 2:
Author.find(:all, :conditions=>['first_name LIKE CONCAT("%", ?, "%")', first_name]


Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...