【问题标题】:How do I create a customer serializer for a hash attribute of a model in Rails?如何在 Rails 中为模型的哈希属性创建客户序列化程序?
【发布时间】:2017-12-14 21:03:30
【问题描述】:

我有以下

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

【问题讨论】:

    标签: ruby-on-rails ruby activerecord serialization ruby-on-rails-5


    【解决方案1】:

    我用过

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2013-06-25
      • 2019-08-14
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多