2011-06-13 24 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