How to properly use the gem 'attr_encrypted' during a migration

104 Views Asked by At

I am adding the attr_encrypted gem to an existing model.

The problem that I am having is that the data on the migration is not converting. When I create a new record, I do see it encrypted.

My migration looks like this.

class AddEncryptedAttributesToUsers < ActiveRecord::Migration[5.2]
  def change
    create_new_fields
    rename_original_fields
    recreate_original_fields
    encrypt_data
    remove_holding_fields
  end

  def create_new_fields
    add_column :users, :encrypted_email, :string
    add_column :users, :encrypted_email_iv, :string
  end

  def rename_original_fields
    rename_column :users, :email, :o_email
  end

  def recreate_original_fields
    add_column :users, :email, :string
  end

  def encrypt_data
    User.find_each do |user|
      user.email              = user.o_email
      user.save
    end
  end

  def remove_holding_fields
    remove_column :users, :o_email, :string
  end

end

In my user model, I added the description keys.

attr_encrypted :email, key: ENV['SECRET_KEY_BASE'].scan(/../).map { |x| x.hex }.pack('C*')

After the migration is run, I can run my user factory, and I see the data adequately encrypted but just not in this migration.

UPDATE I just double check if I create a new user and then close and reopen the console, then I don't see the value of user.email

Thanks for the help

0

There are 0 best solutions below