Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching in rails ( "where column LIKE '%foo%") with Postgres

I have a Person model that includes names, and I want to search these as simply as possible.

Is there a rails/ActiveRecord method along the lines of People.like(:name => "%#{query}%"), like what DataMapper has? I couldn't find anything like this in the ActiveRecord docs but I'm shocked if it's simply not possible.

Currently I have it doing Person.where "name LIKE '%#{query}%'", which works great but is an obvious SQL-injection vulnerability.

Rails 3.2

like image 350
AlexQueue Avatar asked Jul 09 '13 18:07

AlexQueue


1 Answers

Use a parameterized query instead to avoid SQL-injections, like so:

Person.where('name LIKE ?', '%' + query + '%')

Note that the percent signs must be part of the parameter, not the where clause or Rails will escape it and you'll get a syntax error. (At least on postgres.)

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "%"
LINE 1: ...name LIKE %'John...
                     ^
like image 165
Luís Ramalho Avatar answered Sep 28 '22 02:09

Luís Ramalho