Search code examples
ruby-on-railsrubybrakeman

How can I sanitise this SQL query?


I am writing a SQL query in the Post model to search the database to match the query with the body of a post. I am using Brakeman gem to help audit the security of the application, and it has returned the SQL query as vulnerable to injection.

The query,

def self.search(search)
    where("body LIKE '%#{search}%'")
end

Post controller,

if params[:search]
    @posts = Post.search(params[:search]).order("created_at    DESC").paginate(page: params[:page], per_page: 5)
else

Solution

  • You should use this:

    def self.search(search)
    
            where("body LIKE ?", "%#{search}%")
    end