简体   繁体   English

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

[英]How do I create a customer serializer for a hash attribute of a model in Rails?

I have the following 我有以下

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

However, it gives this error: 但是,它给出此错误:

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 #store: http ://api.rubyonrails.org/classes/ActiveRecord/Store.html

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

I used 我用了

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

using the EncryptedType that I had already set up from this answer: https://stackoverflow.com/a/44578417/148844 使用我已经从此答案中设置的EncryptedType: https : //stackoverflow.com/a/44578417/148844

However, if you still want a custom data type serializer, I also found https://www.viget.com/articles/how-i-used-activerecord-serialize-with-a-custom-data-type . 但是,如果您仍然想要自定义数据类型的序列化程序,我还会发现https://www.viget.com/articles/how-i-used-activerecord-serialize-with-a-custom-data-type Basically you have to return an instance of the exact same class as passed to coder: . 基本上,您必须返回与传递给coder:完全相同的类的实例。 I originally tried to subclass JSON , but discovered it was a module, so did not know how to subclass/submodule a module. 我最初尝试对JSON进行子类化,但发现它是一个模块,因此不知道如何对模块进行子类化/子模块化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM