I'm using the attr_encrypted gem for some user data like so:
class User < ApplicationRecord
attr_encrypted :name, key: Encryption['user_name']
attr_encrypted :date_of_birth, key: Encryption['user_date_of_birth'], marshal: true
attr_encrypted :phone_number_home, key: Encryption['user_phone_number_home']
...(some other encrypted attributes)...
end
I'm using devise to create/update the User
's registration info.
The strange behaviour I'm seeing is that every time I update one of the User
's attributes - say name
, all other encrypted attributes also get updated (date_of_birth
, phone_number_home
, etc).
Even a simple rails console set of commands would set off an UPDATE SQL command on all the encrypted fields:
[13] pry(main)> u.changes
=> {"enc_name_iv"=>["T\xD2K\x9C<6\xFC\xAA\x0F\fB?", "U\xCA\xAEB\xFA\x9E\xF3-6\x10\x0E\xBB"],
"enc_name"=>["\xE1\xDA\xAA\xE3\xB6\xEF\xFEY\x06%ea(\xFC\xA1*\x19?\x96\f&1\x84@\xB8H", "x\xAD.\xA2$z\x11\x00\xC7\xCF\xE3\x87i\xC67\x87X\a\xFD\xFE\x84\xA5~4\x97\x8F"],
"name"=>["newer name", "newww name"]}
[14] pry(main)> u.save
(0.2ms) BEGIN
SQL (0.3ms) UPDATE `users` SET `updated_at` = '2017-11-21 20:02:46', `enc_phone_number_home_iv` = x'12cb508e6f2f424196bed890', `enc_phone_number_home` = x'e4bb27954300421cd68fe70f586bd0cef1035d87897e806fbade', `enc_phone_number_mobile_iv` = x'102293734d15da4355264d06', `enc_phone_number_mobile` = x'5343f3c82b47d01fe3f84e20b667f031cb204cd63ada79fd653e', `enc_emergency_contact_phone_iv` = x'1ac5948b7ce93694740cbb10', `enc_physician_phone_number_iv` = x'f9855025778ef564d2a4aad2', `enc_name_iv` = x'55caae42fa9ef32d36100ebb', `enc_name` = x'78ad2ea2247a1100c7cfe38769c637875807fdfe84a57e34978f' WHERE `users`.`id` = 29
This is weird because if I update the name
field only, I am only expecting the enc_name
and enc_name_iv
columns in the database to be updated - it really has nothing to do with the other encrypted fields.
What's more strange is that it seems attr_encrypted
is generating a new set every time for all of the enc_*
attributes as I described above. This behaviour seems not right to me.
My end goal is to track changes to the profile with paper_trail, but as you can imagine, user.versions.last.changeset
is tracking changes to other fields than name
. I think it is attr_encrypted
that is causing the root problem.
Anyone with insight care to share?