2011-06-13 62 views
3

在rails 3.0中,我需要加密现有的文本字段。 有一个包含文本字段“note”的表格备忘录。我已经创建encrypted_note场 并在模型中加入:rails 3.0 attr_encrypted现有数据库

attr_encrypted :note, :key => 'a secret key' 

现在当我加载现有记录的“注意”是空的。我假设attr_encrypted尝试解密......但该字段已经被加密了!

attr_encrypted很适合新记录,但是想知道加密现有记录的最佳策略是什么?

回答

2

请问instance_variable_get('@note')read_attribute('note')有用吗?

如果是的话,你也许可以做到在Rails的控制台是这样的:

User.all.each do |user| 
    user.note = user.instance_variable_get('@note') 
    user.save 
end 
+0

read_attribute很好,谢谢!...我试着在与encrypted_note同时获得popul ated清除数据库中的“note”字段做user.write_attribute('note',''),但我得到这个错误:私人方法'write_attribute'调用...任何想法? – Alpha 2011-06-15 07:22:21

2

这里是清除加密列加密一个获取填充的伎俩! 在模型中添加:

before_update :clear_note 

def clear_note 
    if encrypted_note != nil && read_attribute('note') != nil 
    write_attribute('note','') 
    end 
end 
0

假设你开始你的模型Thing与未加密属性note

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