我有以下自定義型別:
class EncryptedTextType < ActiveRecord::Type::Text
def deserialize(encrypted_value)
return unless encrypted_value
Encryptor.decrypt(encrypted_value)
end
def serialize(plain_value)
return unless plain_value
Encryptor.encrypt(plain_value)
end
end
ActiveRecord::Type.register(:encrypted_text, EncryptedTextType)
這作業正常,但總是讓我的記錄變臟。每次我從使用這種型別的資料庫加載記錄時,它都會立即變臟。
這是記錄:
class Organization < ApplicationRecord
attribute :access_key, :encrypted_text
[1] pry(main)> organization = Organization.last
Organization Load (0.7ms) SELECT "organizations".* FROM "organizations" ORDER BY "organizations"."created_at" DESC, "organizations"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Organization:0x00007fe000628198
id: "c968db2e-dd5a-4016-bf3d-d6037aff4d7b",
[2] pry(main)> organization.changed?
=> true
[3] pry(main)> organization.changes
=> {"access_key"=>["de07e...", "de07e..."]}
奇怪的是,即使訪問密鑰沒有改變,AR 仍然認為它改變了。
uj5u.com熱心網友回復:
供將來參考:我忘了實施 changed_in_place?
def changed_in_place?(raw_old_value, new_value)
raw_old_value != serialize(new_value)
end
這做到了
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364008.html
