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
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...
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With