class EncodeCandidateEmails < ActiveRecord::Migration[5.0] def change sql = "select id, email from candidates;" candidates = ActiveRecord::Base.connection.execute(sql).to_h candidates.each do |id, email| sql = if base64?(email) # going down - decrypt "UPDATE candidates set email = '#{CryptSerializer.load email}' WHERE id = #{id};" else # going up - encrypt emails "UPDATE candidates set email = '#{CryptSerializer.dump email}' WHERE id = #{id};" end ActiveRecord::Base.connection.execute(sql) end end private def base64? string Base64.urlsafe_decode64 string true rescue ArgumentError false end end