0

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

MZaragoza
  • 10,108
  • 9
  • 71
  • 116
  • Not sure if it's a copy/paste error, but you're referring to the `admins` table in the `rename_original_fields` method, but `users` table everywhere else. But also: I don't think you want to add another `email` column? The attribute is handled via `encrypted_email` instead. – pat Apr 13 '23 at 05:59
  • 1
    This is kind of a side note but there is no point in breaking up a migration into a bunch of methods. It's only supposed to be used for a short period of time and then be deleted. If you do feel the temptation to do some it should be telling your that you're doing to much in a single migration. – max Apr 13 '23 at 11:44
  • 1
    Also updating the existing records should be done via a rake task and not a migration. If you have a lot of records it could take a long time to run which could lead to the migration timing out and leaving the schema in a broken state. – max Apr 13 '23 at 11:46
  • @pat ty, yes, that was a copy-paste error. – MZaragoza Apr 13 '23 at 12:27
  • *"but just not in this migration"* could you describe your issue in a bit more detail? Is the existing data not converted? Do you get errors? What exactly is the problem you're facing? – 3limin4t0r Apr 13 '23 at 12:35
  • Breaking up migrations into many functions this way makes them very hard to read. They should be written in side the `change` method, which reads top-to-bottom. – user229044 Apr 13 '23 at 14:46

0 Answers0