0

は私が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

答えて

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をサブクラス化しようとしましたが、それがモジュールであることを発見したので、モジュールをサブクラス化/サブモジュール化する方法がわかりませんでした。

関連する問題