自定义类型总是改变记录,让它变脏
Posted
技术标签:
【中文标题】自定义类型总是改变记录,让它变脏【英文标题】:custom type always change the record, leaving it dirty 【发布时间】:2021-12-31 11:37:15 【问题描述】:我有以下自定义类型:
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 仍然认为它改变了。
【问题讨论】:
【参考方案1】:供以后参考:我忘了实现changed_in_place?
def changed_in_place?(raw_old_value, new_value)
raw_old_value != serialize(new_value)
end
成功了
【讨论】:
以上是关于自定义类型总是改变记录,让它变脏的主要内容,如果未能解决你的问题,请参考以下文章