如何在 Rails 中为模型的哈希属性创建客户序列化程序?



我有以下内容

class User < ApplicationRecord
class JSONEncrypted
def load(dbtext)
JSON.load dbtext.decrypt
end
def dump(hash)
(JSON.dump hash).encrypt
end
end
store :profile, accessors: [:dob], coder: JSONEncrypted

但是,它给出了此错误:

irb(main):006:0> u=User.first
irb(main):009:0> u.dob=Date.new(1970,1,1)
irb(main):010:0> u.dob
=> Thu, 01 Jan 1970
irb(main):011:0> u.profile
=> {"dob"=>Thu, 01 Jan 1970}
irb(main):017:0> JSON.dump u.profile
=> "{"dob":"1970-01-01"}"
irb(main):018:0> (JSON.dump u.profile).encrypt
=> "ZKr3SnJDsmdPllUpkveU0Ds6s2QO1zH7sPmquWZDEL0PYbvaBO6k8Y26+F99oEZy"
irb(main):012:0> u.validate
=> true
irb(main):015:0> u.save
ActiveRecord::SerializationTypeMismatch: Attribute was supposed to be a User::JSONEncrypted, but was a ActiveSupport::HashWithIndifferentAccess. -- {"dob"=>Thu, 01 Jan 1970}

#store:http://api.rubyonrails.org/classes/ActiveRecord/Store.html

客户序列化:https://apidock.com/rails/ActiveRecord/AttributeMethods/Serialization/ClassMethods/serialize#1343-Custom-serialization

我用过

attribute :profile, :encrypted
store :profile, accessors: [:dob], coder: JSON

使用我已经从这个答案中设置的加密类型:https://stackoverflow.com/a/44578417/148844

但是,如果您仍然想要自定义数据类型序列化程序,我也发现了 https://www.viget.com/articles/how-i-used-activerecord-serialize-with-a-custom-data-type。基本上,您必须返回与传递给coder:完全相同的类的实例。我最初尝试子类JSON,但发现它是一个模块,所以不知道如何子类/子模块一个模块。

最新更新