Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to encrypt existing data with Ruby on Rails?

I want to encrypt some fields of some tables from my db. If I add encrypts :'field_name' to model class, it won’t encrypt data already added to db. I guess I have to write a migration that will do this. What methods or Rails modules should I use? I couldn’t find it in Encryption in Rails Guide.
Thank you.

I’ve tried to read Rails Guides and documentation, but it didn’t help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add a new column to your model’s database table and configure your model to encrypt that new column.

# in a migration
add_column :model_name, :attribute_name_new, :string

# in the model
encrypts :attribute_name_new

Once that is set up, copy the data over from the legacy column to the new encrypted column:

# in a Rake task or simply in the Rails console:
ModelName.find_each do |record|
  record.update(attribute_name_new: record.attribute_name)
end

And as a last step, delete the old column and rename the new column to the original attribute name.

# in a migration
remove_column :model_name, :attribute_name
rename_column :model_name, :attribute_name_new, :attribute_name

Depending on the size of your database table and if a short downtime while running these steps is okay, you might need or not need additional changes to your model to keep both columns in sync for a longer period of time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading