15

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

2
  • Isnt postgres use ILIKE instead of LIKE ? Commented Jul 9, 2013 at 18:13
  • 3
    "The key word ILIKE can be used instead of LIKE to make the match case-insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension." Commented Jul 9, 2013 at 18:16

1 Answer 1

45

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...
                     ^
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.