From 7ccd91ff6670c76ac026e9f8e3b326e24d37da0f Mon Sep 17 00:00:00 2001 From: Matijs van Zuijlen Date: Fri, 28 Jun 2024 13:56:55 +0200 Subject: [PATCH] Make Content.searchstring scope code more transparent Avoiding string concatenation in this scope prevents Brakeman from flagging it as a potential SQL injection. --- app/models/content.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/app/models/content.rb b/app/models/content.rb index 59e9ce39..2623508a 100644 --- a/app/models/content.rb +++ b/app/models/content.rb @@ -25,10 +25,15 @@ class Content < ApplicationRecord scope :drafts, -> { where(state: "draft").order("created_at DESC") } scope :no_draft, -> { where.not(state: "draft").order("published_at DESC") } scope :searchstring, lambda { |search_string| + result = where(state: "published") + tokens = search_string.split(" ").map { |c| "%#{c.downcase}%" } - matcher = "(LOWER(body) LIKE ? OR LOWER(extended) LIKE ? OR LOWER(title) LIKE ?)" - template = "state = ? AND #{([matcher] * tokens.size).join(" AND ")}" - where(template, "published", *tokens.map { |token| [token] * 3 }.flatten) + tokens.each do |token| + result = result + .where("(LOWER(body) LIKE ? OR LOWER(extended) LIKE ? OR LOWER(title) LIKE ?)", + token, token, token) + end + result } scope :published_at_like, lambda { |date_at|