# Quotes cause SQL havoc

**URL:** <https://www.ruby-forum.com/t/quotes-cause-sql-havoc/140912>\
**Category:** Rails\
**Created:** [June 19, 2008, 7:38pm UTC](https://www.ruby-forum.com/t/quotes-cause-sql-havoc/140912 "2008-06-19T19:38:12Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dino\_d](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b5ac83/32.png) [@dino\_d](https://www.ruby-forum.com/u/dino_d)\
**Post date:** [June 19, 2008, 7:38pm UTC](https://www.ruby-forum.com/t/quotes-cause-sql-havoc/140912/1 "2008-06-19T19:38:12Z")

</div>

Hi-

I cannot seem to find an answer to this. I have a simple question  
with quotes- I want to allow apostrophes in a string in a model. I  
then want to allow searching on that field. In ActiveRecord, when I  
create a search using find, and say

:conditions=\> “title like ‘%#{query}%’ or body like ‘%#{query}%’”

where query is the search string, I get an exception when the user  
enters an apostrophe because it messes with the SQL (the apostrophe  
closes the query). How do I escape apostrophes but keep them in there  
so they’ll match records in the db?

Thanks,  
Dino

---

<div class="post-metadata">

**Author:** ![dino\_d](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b5ac83/32.png) [@dino\_d](https://www.ruby-forum.com/u/dino_d)\
**Post date:** [June 19, 2008, 7:50pm UTC](https://www.ruby-forum.com/t/quotes-cause-sql-havoc/140912/2 "2008-06-19T19:50:35Z")

</div>

Hi Dino,

You can use ActiveRecord’s built in escaping by changing that code  
slightly - you can pass arguments separately from your condition  
string:

:conditions =\> [“title LIKE ?”, “%#{query}%”]

If you need to use the ‘query’ variable more than once, you can use  
placeholders:

:conditions =\> [“title LIKE :query OR body LIKE :query”, {:query =\>  
“%#{query}%”}]

This is also safer as you’ll be protected from SQL injection attacks.

Hope that helps,

Steve

---

<div class="post-metadata">

**Author:** ![dino\_d](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b5ac83/32.png) [@dino\_d](https://www.ruby-forum.com/u/dino_d)\
**Post date:** [June 19, 2008, 8:02pm UTC](https://www.ruby-forum.com/t/quotes-cause-sql-havoc/140912/3 "2008-06-19T20:02:56Z")

</div>

Thanks Steve! Works great.

Dino
