Secure ActiveRecord Request

I am trying to write a LIKE request.

I read that pure string queries are unsafe, however I could not find any documentation that would explain how to write a secure LIKE Hash Query query.

Is it possible? Do I have to manually defend against SQL Injection?

+44
ruby activerecord ruby-on-rails-4
Sep 29 '14 at 7:17
source share
4 answers

To verify that the query string is cleared correctly, use array or hash syntax to describe your conditions:

Foo.where("bar LIKE ?", "%#{query}%") 

or

 Foo.where("bar LIKE :query", query: "%#{query}%") 

If it is possible that query may contain the % character, then you need to sanitize the query with sanitize_sql_like first:

 Foo.where("bar LIKE ?", "%#{sanitize_sql_like(query)}%") Foo.where("bar LIKE :query", query: "%#{sanitize_sql_like(query)}%") 
+85
Sep 29 '14 at 7:27
source share

Using Arel, you can execute this safe and portable request:

 title = Model.arel_table[:title] Model.where(title.matches("%#{query}%")) 
+9
Jan 02 '17 at 14:08
source share

For PostgreSQL will be

 Foo.where("bar ILIKE ?", "%#{query}%") 
+4
Dec 6 '15 at 15:31
source share

You can do

 MyModel.where(["title LIKE ?", "%#{params[:query]}%"]) 
+1
Sep 29 '14 at 7:27
source share



All Articles