# Implementing Safe ActiveRecord Like Queries for Rails

DevFeed: [Implementing Safe ActiveRecord Like Queries for Rails](<https://devfeed.tech/articles/implementing-safe-activerecord-like-queries-for-rails-28243.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2019/11/11/implementing-safe-activerecord-like-queries.html>)

Author: Fuzzygroup

Published: 2019-11-11T00:00:00Z

Content type: article

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Ruby on Rails](<https://devfeed.tech/topics/ruby-on-rails.md>), [like](<https://devfeed.tech/topics/like.md>), [Database](<https://devfeed.tech/topics/database.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [like](<https://devfeed.tech/tags/like.md>), [rails](<https://devfeed.tech/tags/rails.md>)

## AI overview

The excerpt shows a Rails ActiveRecord substring search using Arel: build a column reference with `Metric.arel_table[:note]`, then pass `note.matches("%#{@q}%")` to `where`. Its example takes `@q` from `params[:metric][:q]` and adds user scoping, descending date order, a limit, and pagination. Although the text raises SQL injection as a concern, it does not explain or demonstrate how this Arel pattern prevents injection.

## Source excerpt

In any SQL based database, a like query is generally an SQL injection attack waiting to happen because the underlying sql statement looks like this: SELECT id FROM posts WHERE name LIKE '%foo%' Note: A 30 year old thank you goes out to InfoWorld and Joe Celko who beat into his reader's brains the concept of capitalizing SQL statements for better legibility. Thank you Joe. A seemingly solid StackOverflow post gives this recommendation: title = Model.arel_table[:title] Model.where(title.matches("%#{query}%")) Please note that Model needs to be replaced with the name of your table. Let's say that our table was named Metric and we have a normal simple_form object for Metric coming into our Rails app with a parameter named q and we have a real world Rails app with a limit clause and pagination. Here's how this would look: @q = params[:metric][:q] note = Metric.arel_table[:note] @metrics = current_user.metrics.where(note.matches("%#{@q}%")).order("date_created_at desc").limit(@limit).page(params[:page]) So: @q represents the incoming query note represents the field in our Metrics table that we want to search agains @metrics is the collection of data returned by the search and the where clause is "note.matches("%#{@q}%")" to find any instances of the term @q within the note field