【问题标题】:Object changed handle with custom Serializer使用自定义序列化程序更改对象的句柄
【发布时间】:2019-05-17 16:10:34
【问题描述】:

我已经定义了一个自定义序列化器

class CustomSerializer
  def self.dump(obj)
    obj.to_h
  end

  def self.load(obj)
    CustomClass.new(obj)
  end
end

并用于活动记录模型

class Klass < ActiveRecord::Base
   serialize :my_column, CustomSerializer
end 

现在当使用 Klass k = Klass.first 的对象时,我总是看到 k.changed? = true

我知道这是因为我定义的序列化程序引入的类引用

k.my_column_was # #<CustomClass:0x00007fd9063d6288>
k.my_column # #<CustomClass:0x00007fd9080d9088> 

如何解决此问题?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    Rails 5 Attributes API 将允许您操纵 dirty tracking 的处理方式。

    这是针对特定领域序列化的推荐方法。

    对于更复杂的情况,例如与应用程序域对象之间的转换,请考虑使用 ActiveRecord::Attributes API。

    不幸的是,对于

    序列化属性的一个显着副作用是模型将在每次保存时更新,即使它不是脏的。

    你偶然发现了什么

    【讨论】:

    • 如何在 Rails 5 中操作?我想保留k.my_column # #&lt;CustomClass:0x00007fd9063d6288&gt;
    • @ayushlodhi 来帮助实现我需要知道 my_column 本身是什么,以便我们可以实现适当的类型转换方案。如果您想自己研究一下,只需 google rails attributes api(大量文档和文章)。例如这里是 JSON 类型的实现方式github.com/rails/rails/blob/master/activerecord/lib/…
    • 我现在明白了。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多