Matching patterns in rails ("where is the LIKE column"% foo% ") with Postgres

I have a Person model that includes names, and I want to find them as simple as possible.

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

I am currently running Person.where "name LIKE '%#{query}%'" , which works fine, but is an obvious SQL injection vulnerability.

Rails 3.2

+7
ruby-on-rails activerecord postgresql
source share
1 answer

Use a parameterized query to avoid SQL injection, for example:

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

Note that percent signs should be part of the parameter, not a where clause or Rails to avoid it, and you will get a syntax error. (At least in postgres.)

 ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "%" LINE 1: ...name LIKE %'John... ^ 
+27
source share

All Articles