微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

rails 3.0 attr_encrypted现有数据库

如何解决rails 3.0 attr_encrypted现有数据库

| 在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
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。