Rails 7 introduced a powerful feature to help developers protect sensitive user data: Active Record Encryption. This application-level encryption secures specified model attributes without relying solely on the database layer. In this post, we'll explore how it works and how to use it effectively.

💡 What Is Active Record Encryption?

Active Record Encryption adds a layer of encryption between your Rails app and your database. You define which fields are sensitive, and Rails takes care of encrypting and decrypting them transparently.

“Active Record Encryption exists to protect sensitive information in your application… you define what constitutes sensitive information at the code level.”
Rails Guides

This encryption is application-side, meaning the database never sees unencrypted values.

🔒 Why Encrypt at the Application Level?

While many applications encrypt data at rest (e.g., at the disk or database level), Active Record Encryption provides more granular and powerful protection:

  • ✅ Prevents exposure in logs, backups, and unauthorized DB access
  • ✅ Offers field-level control
  • ✅ Seamlessly integrates with Active Record

This approach is especially useful for personally identifiable information (PII), financial details, or health-related data.

⚙️ Getting Started

1. Generate Encryption Keys

Rails offers a built-in generator to bootstrap the required encryption keys:

bin/rails db:encryption:init

This will generate base key and deterministic key values and save them into config/master.key or ENV.

2. Declare Encrypted Attributes

To encrypt specific model attributes, use:

class User < ApplicationRecord
  encrypts :email, :ssn
end

That’s it — Rails now transparently encrypts/decrypts those fields when reading/writing to the database.

3. Working with Encrypted Fields

Encrypted fields can be queried with deterministic encryption, using:

User.find_by(email: 'someone@example.com')

If you only use non-deterministic encryption, querying is not supported directly.

4. Advanced Configurations

  • Custom keys per attribute
  • Encrypt only on write
  • Support for blind indexes for secure queries

You can refer to the official guide for more detailed configurations and examples.

✅ Best Practices

  • Never commit secrets to version control
  • Use environment variables or credential files for encryption keys
  • Encrypt only what you need — avoid over-encryption
  • Test both encryption and decryption flows thoroughly

📚 Resources