Search code examples
ruby-on-railsrubyencryption

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.


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.