自定义类型总是更改记录,使其变脏
custom type always change the record, leaving it dirty
我有以下自定义类型:
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 [["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 仍然认为它改变了。
供将来参考:我忘了实施 changed_in_place?
def changed_in_place?(raw_old_value, new_value)
raw_old_value != serialize(new_value)
end
成功了
我有以下自定义类型:
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 [["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 仍然认为它改变了。
供将来参考:我忘了实施 changed_in_place?
def changed_in_place?(raw_old_value, new_value)
raw_old_value != serialize(new_value)
end
成功了