Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe ActiveRecord like query

I'm trying to write LIKE query.

I read that pure string quires aren't safe, however I couldn't find any documentation that explain how to write safe LIKE Hash Query.

Is it possible? Should I manually defend against SQL Injection?

like image 538
Gal Weiss Avatar asked Sep 29 '14 07:09

Gal Weiss


People also ask

Is ActiveRecord an ORM?

ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.

Is ActiveRecord a framework?

1.3 Active Record as an ORM Framework Active Record gives us several mechanisms, the most important being the ability to: Represent models and their data. Represent associations between these models. Represent inheritance hierarchies through related models.

What does ActiveRecord base mean?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is ActiveRecord Query Interface in rails?

Active Record insulates you from the need to use SQL in most cases. Active Record will perform queries on the database for you and is compatible with most database systems, including MySQL, MariaDB, PostgreSQL, and SQLite.


1 Answers

To ensure that your query string gets properly sanitized, use the array or the hash query syntax to describe your conditions:

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

or:

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

If it is possible that the query might include the % character and you do not want to allow it (this depends on your usecase) then you need to sanitize query with sanitize_sql_like first:

Foo.where("bar LIKE ?", "%#{sanitize_sql_like(query)}%") Foo.where("bar LIKE :query", query: "%#{sanitize_sql_like(query)}%") 
like image 136
spickermann Avatar answered Nov 12 '22 21:11

spickermann