Picture of the author

GAURAV VARMA

← BACK TO BLOG

Rails 7 adds Active Record Encryption for sensitive data


Before Rails 7, encrypting attributes in Active Record models meant relying on third-party gems like lockbox. While effective, these added external dependencies and complexity.

Rails 7 brings first-class Active Record Encryption support, letting you securely store sensitive data with minimal setup and without external gems.

How Active Record Encryption works

You can now mark model attributes to be encrypted like this:

1class User < ApplicationRecord
2  encrypts :passport_number
3end

Once configured, Rails will automatically encrypt passport_number before saving it to the database and decrypt it transparently when reading.

Behind the scenes, Rails uses AES-GCM encryption (non-deterministic by default) and the new EncryptableRecord concern.

Setup

To get started, you’ll need to initialize encryption keys. Run the following command:

1bin/rails db:encryption:init

This generates keys and salts in config/credentials.yml.enc:

1active_record_encryption:
2  primary_key: <generated-key>
3  deterministic_key: <generated-key>
4  key_derivation_salt: <generated-salt>

These secrets are required to securely encrypt and decrypt the data.

Example in action

1user = User.create(name: "Gaurav", passport_number: "DK76FS87DF")

When saved, the value of passport_number is encrypted in the DB But when queried:

1User.last.passport_number
2# => "DK76FS87DF"

Features

  • Built-in AES-GCM encryption
  • Per-attribute encryption support
  • Key rotation
  • Optional deterministic mode for searchable encrypted fields
  • No extra gems required

References

Summary

Rails 7 introduces native, secure encryption for Active Record attributes—making it easier than ever to protect sensitive user data like SSNs, credit card numbers, or passport IDs. It’s opinionated, flexible, and ready for production use out of the box.