2 ways to use LIKE queries with wildcards safely in Rails finders
by specialj 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]