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

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

Your email address will not be published. Required fields are marked *