2017-07-30 35 views
0

我有一個加密類型在我的模型如何獲取模型的原始預反序列化值?

attribute :name, :encrypted 

這是

class EncryptedType < ActiveRecord::Type::Text 

,並實現#serialize#deserialize#changed_in_place?

如何在反序列化之前從數據庫中獲取原始值?

我想創建一個rake任務來加密數據庫中的字段被加密之前存在的值。所以在加密之前,name字段包含Bob。在加密代碼後,讀取該值將產生一個錯誤(捕獲),返回一個空字符串。我想讀取原始值並將其設置爲普通屬性,以便對其進行加密。加密後,該字段看起來像UD8yDrrXYEJXWrZGUGCCQpIAUCjoXCyKOsplsccnkNc=

我想要類似user.name_rawuser.raw_attributes[:name]

+1

如何定義一個名爲'unencrypted'的方法來處理'encrypted'屬性?所以你可以參考這個方法而不是原來的屬性。這看起來更加緊密,一旦'encrypt'名字意味着數據將被加密。 –

回答

1

ActiveRecord::AttributeMethods::BeforeTypeCast

提供了一種類型轉換和反序列化

之前讀取屬性的值並具有read_attribute_before_type_castattributes_before_type_cast。此外,

它宣佈了與* _before_type_cast後綴

因此,例如所有屬性的方法:

User.last.created_at_before_type_cast # => "2017-07-29 23:31:10.862924" 
User.last.created_at_before_type_cast.class # => String 
User.last.created_at # => Sat, 29 Jul 2017 23:31:10 UTC +00:00 
User.last.created_at.class # => ActiveSupport::TimeWithZone 
User.last.attributes_before_type_cast # => all attributes before type casting and such 

我想這將與您的自定義加密類型工作

0

由於SimpleLime建議...

namespace :encrypt do 
    desc "Encrypt the unencrypted values in database" 
    task encrypt_old_values: :environment do 
    User.all.each do |user| 
     if user.name.blank? && ! user.name_before_type_cast.blank? 
     User.class_variable_get(:@@encrypted_fields).each do |att| 
      user.assign_attributes att => user.attributes_before_type_cast[att.to_s] 
     end 
     user.save validate: false 
     end 
    end