# How to SQL-escape user input/do SQL-LIKE thru AR?

**URL:** <https://www.ruby-forum.com/t/how-to-sql-escape-user-input-do-sql-like-thru-ar/103577>\
**Category:** Rails\
**Created:** [May 8, 2007, 2:43am UTC](https://www.ruby-forum.com/t/how-to-sql-escape-user-input-do-sql-like-thru-ar/103577 "2007-05-08T02:43:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sbeam](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/258eb7/32.png) [@sbeam](https://www.ruby-forum.com/u/sbeam)\
**Post date:** [May 8, 2007, 2:43am UTC](https://www.ruby-forum.com/t/how-to-sql-escape-user-input-do-sql-like-thru-ar/103577/1 "2007-05-08T02:43:31Z")

</div>

AR insists on escaping user input when using the find() method, which is  
commendable. But what if you need the equivalent of

SELECT \* FROM user WHERE email LIKE ‘%#{params[:terms]}%’

??

putting  
:conditions =\> [“email LIKE ‘%?%’”, params[:terms]]

will asplode for obvious reasons.

Also, what if I have an array coming from the form and what to put the  
values into a IN() clause, i.e

…WHERE dept\_id IN (1,2,3,4,5)

doing  
:conditions =\> [“dept\_id IN (?)”, params[:email].join(’,’)]

will not do anything useful.

So in short, I need access to the function that allows me to directly  
escape user input myself. AWDWROR and G$$gle were no help finding it.

thanks  
Sam

---

<div class="post-metadata">

**Author:** ![sbeam](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/258eb7/32.png) [@sbeam](https://www.ruby-forum.com/u/sbeam)\
**Post date:** [May 8, 2007, 11:53am UTC](https://www.ruby-forum.com/t/how-to-sql-escape-user-input-do-sql-like-thru-ar/103577/2 "2007-05-08T11:53:55Z")

</div>

sbeam wrote:

> will asplode for obvious reasons.

Taken from AWDWROR:

Using Like Clauses  
You might be tempted to do something like the following to use  
parameterized  
like clauses in conditions:

# Doesn’t work

User.find(:all, :conditions =\> [“name like ‘?%’” , params[:name]])  
Rails doesnï¿½t parse the SQL inside a condition and so doesnï¿½t know that  
the  
name is being substituted into a string. As a result, it will go ahead  
and add  
extra quotes around the value of the name parameter. The correct way to  
do  
this is to construct the full parameter to the like clause and pass that  
parameter  
into the condition.

# Works

User.find(:all, :conditions =\> [“name like ?” , params[:name]+"%" ])

> Also, what if I have an array coming from the form and what to put the  
> values into a IN() clause, i.e
> 
> …WHERE dept\_id IN (1,2,3,4,5)
> 
> doing  
> :conditions =\> [“dept\_id IN (?)”, params[:email].join(’,’)]
> 
> will not do anything useful.

:conditions =\> [“dept\_id IN (?)”, params[:email]]

AR will automatically join your array (it must be an array!).

Tiago M.
