Skip to content
All articles

SQL Injection Vulnerabilities in Rails

23 October 2024 · 1 min read · Rubycode

When we first start learning Ruby on Rails, one of the things we quickly pick up is that Active Record helps protect our applications from SQL injection attacks. However, even with this powerful ORM, our apps can still become vulnerable if we’re not careful with how we write our code.

BAD PRACTICE

class UsersController < ApplicationController
  def index
    @users = User.where("users.name = #{params[:name]}")
  end
end

What would happen if a malicious user passed in the following URL parameter:

name=John;DROP TABLE USERS;

The code would execute exactly what the attacker has input, causing the entire USERS table to be dropped from your database—leaving you with potentially devastating data loss.

GOOD PRACTICE

class UsersController < ApplicationController
  def index
    @users = User.where(name: params[:name])
  end
end

In this example, Rails automatically escapes the input, ensuring that any user-provided data is safely handled, preventing harmful SQL code from being executed

This is a simple example, but it shows how easy it is to make a mistake when using direct SQL queries in your Rails app. If you ever need to use raw SQL, always make sure to properly sanitize any user input to avoid security risks like SQL injection.

Need engineers who write code like this?

We place vetted developers, designers, QA and delivery specialists with enterprises and startups across the EU. Tell us what you need and we'll shortlist people who fit.

Book a 30-minute call