# 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: tutorial

Language: en

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

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [SQL](<https://devfeed.tech/topics/sql.md>), [Databases](<https://devfeed.tech/topics/databases.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [database](<https://devfeed.tech/tags/database.md>), [limit](<https://devfeed.tech/tags/limit.md>), [parameter](<https://devfeed.tech/tags/parameter.md>), [rails](<https://devfeed.tech/tags/rails.md>), [sql](<https://devfeed.tech/tags/sql.md>), [table](<https://devfeed.tech/tags/table.md>)

## AI overview

A Rails tutorial explains how to build safer ActiveRecord LIKE queries using Arel table fields and parameterized query construction. It demonstrates searching a Metric model's note field with filtering, ordering, limits, and pagination.

## 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