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?
ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code.
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
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)}%")
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