Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 564
abobik2000 Avatar asked Oct 22 '25 05:10

abobik2000


1 Answers

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.

like image 121
spickermann Avatar answered Oct 23 '25 19:10

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!