Search code examples
ruby-on-railsrubypostgresqlruby-on-rails-5attr-encrypted

Updating existing unencrypted records with attr_encrypted


How do I update existing records that were previously unencrypted with the gem attr_encrypted.

I currently have the column text in a table called AppointmentNote which is just a string. I now want to have a column called note which is encrypted (with attr_encrypted).

I've added the columns

encrypted_note encrypted_note_iv

This works well when I do AppointmentNote.create(note: "blah") it encrypts properly, and any further updates on that record work well.

The problem is with records created prior to the migration. How do i migrate all the data from the column text into the new encrypted columns encrypted_note and encrypted_note_iv

This is the model

class AppointmentNote < ApplicationRecord
  attr_encrypted_options.merge!(encode: true)
  attr_encrypted :note, key: SOME_KEY
  ...
end

If i do the what I thought the obvious solution was it simply roll back AppointmentNote.first.update(note: "rawr")

Thanks


Solution

  • You should be able to just update them all with a save. Something like:

    rails g migration update_apartment_notes_note_for_encryption

    Open that generated file.

    def change
      AppointmentNote.find_each do |apartment_note|
        apartment_note.save 
      end
    end
    

    rake db:migrate

    Note: Using find_each is wiser than all if you have tons of records. The goal here is to iterate over them.