问题描述
|
在Rails 3.0中,我需要加密现有的文本字段。
那里有一个表格备注,其中包含文本字段““ note \”。我已经创建了一个“ encrypted_note”字段
并在模型中添加:
attr_encrypted :note,:key => \'a secret key\'
现在,当我加载现有记录时,\“ note \”为空。我假设attr_encrypted尝试解密...但是该字段已经被加密了!
attr_encrypted可以很好地用于新记录,但是想知道加密现有记录的最佳策略是什么吗?
解决方法
instance_variable_get(\'@note\')
或read_attribute(\'note\')
是否起作用?
如果是这样,您可能可以在Rails控制台中执行以下操作:
User.all.each do |user|
user.note = user.instance_variable_get(\'@note\')
user.save
end
, 这是在填充加密列时清除未加密列的技巧!
在模型中添加:
before_update :clear_note
def clear_note
if encrypted_note != nil && read_attribute(\'note\') != nil
write_attribute(\'note\',\'\')
end
end
, 假设您从模型“ 5”开始,并使用未加密的属性“ 6”。
1)添加一个迁移以添加字段encrypted_note
并填充它
class EncryptThing < ActiveRecord::Migration
def up
rename_column :things,:note,:old_note
add_column :things,:encrypted_note,:string
# if you want to use per-attribute iv and salt:
# add_column :things,:encrypted_note_iv,:string
# add_column :things,:encrypted_note_salt,:string
Thing.find_each do |t|
t.note = t.old_note
t.save
end
remove_column :things,:old_note
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
2)在模型中添加一行以指定加密属性:
attr_encrypted :note,:key => Rails.application.config.key
# if you want to use per-attribute iv and salt,add this to the line above:
#,:mode => :per_attribute_iv_and_salt
3)运行您的迁移
rake db:migrate