Safe ActiveRecord like query

RubyActiverecordRuby on-Rails-4

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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)}%")

Solution 2 - Ruby

Using Arel you can perform this safe and portable query:

title = Model.arel_table[:title]
Model.where(title.matches("%#{query}%"))

Solution 3 - Ruby

For PostgreSQL it will be

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

Solution 4 - Ruby

In case if anyone performing search query on nested association try this:

Model.joins(:association).where(
   Association.arel_table[:attr1].matches("%#{query}%")
)

For multiple attributes try this:

Model.joins(:association).where(
  AssociatedModelName.arel_table[:attr1].matches("%#{query}%")
    .or(AssociatedModelName.arel_table[:attr2].matches("%#{query}%"))
    .or(AssociatedModelName.arel_table[:attr3].matches("%#{query}%"))
)
 

Don't forget to replace AssociatedModelName with your model name

Solution 5 - Ruby

You can do

MyModel.where(["title LIKE ?", "%#{params[:query]}%"])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGal WeissView Question on Stackoverflow
Solution 1 - RubyspickermannView Answer on Stackoverflow
Solution 2 - RubyPedro RoloView Answer on Stackoverflow
Solution 3 - RubyKhogaView Answer on Stackoverflow
Solution 4 - RubyRajan Verma - AarvyView Answer on Stackoverflow
Solution 5 - RubySanthoshView Answer on Stackoverflow