Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 - Prevent SQL injection using LIKE operator in SQL query

I'd like to use the following query for my Rails 4 application but am concerned about SQL injection attacks:

@persons = People.where("persons.name LIKE ?", "%#{params[:search]}%")

Can somebody show me the safe way to write the above statement? I've tried the following but am not sure if it is SQL-injection-proof:

search = "%" + params[:search] + "%"
@persons = People.where("persons.name LIKE ?", search)

Thanks!

like image 931
Vee Avatar asked Aug 21 '14 00:08

Vee


1 Answers

Your examples are fine, as zishe said.

Whenever you use question marks to a method and pass another parameters as the search query, it sanitizes your query string.

It is dangerous when you manually do string concatenations to create your query, for example:

Project.where("name = '#{params[:name]}'")

Click here for more information

like image 187
Migore Avatar answered Oct 19 '22 06:10

Migore