Skip to content

SQL Injection Vulnerabilities in Rails

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 w...

Rubycode

23 October 2024 · 1 min read

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.

Share

More from the blog

  • Engineering

    How to write an implementation plan your team can trust

    What every implementation plan for a Rails feature must have, from the decisions only people can make to safe migrations, testable acceptance criteria and a sign-off, and how to make your team follow it every time with questions, settings and guards in code.

    06 October 2026 · 11 min read

  • AI Engineering

    Where Is the Engineering Work Now? Redesigning Development Around AI

    Agents already write most of the code in a sprint, yet we still run it as if every developer types their own ticket. Where the real engineering work is today, and what changes when you redesign the process around AI.

    02 October 2026 · 5 min read

  • Gems

    The agents write the code. Your team decides what gets built.

    plan_driven is an open source Ruby gem that takes a Rails feature from an approved implementation plan to merged, tested pull requests, with one Cursor agent per ticket and guards written in Ruby at every step.

    30 September 2026 · 17 min read

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.

Ivan Blazevic, CEO of Rubycode

Ivan Blažević

Connect with our CEO — experienced senior staff engineer and Rails developer