How to use wildcards in an active record where clause while protecting against sql injection

activerecord, ruby-on-rails

Solution

You should modify your query like this

User.where("first_name LIKE (?)", "%#{first_name}%")

Problem

From the rails active record querying guide on sql injection This code is highly preferable: Client.where("orders_count = ?", params[:orders]) to this code: Client.where("orders_count = #{params[:orders]}") My problem is I want to use a LIKE clause with a wildcard. My old query looks like this - ``` User.where("first_name LIKE '%#{first_name}%'") ``` Which is vulnerable to sql injection, but if I do this: ``` User.where("first_name LIKE '%?%'", first_name) ``` Then the resulting sql looks like: ``` SELECT "users".* FROM "users" WHERE (first_name LIKE '%'michael'%') ``` which is invalid due to the extra single quotes. What is the best way to use wildcards and a LIKE clause but also protect against sql injection attacks?

Original source