我有一个
Entry
类,它有一个 Charge
属性,当从数据库读取时,我想将其实例化为 Charge
对象:
class Entry < ActiveRecord::Base
serialize :charge, Charge
end
class Charge
# Reading from the db as a string
def self.load(str)
str.nil? ? nil : new(str)
end
# Writing to the db as a string
def self.dump(chg)
chg.nil? ? nil : chg.to_s
end
end
这很好用:
ent = Entry.find(1)
ent.charge.class => Charge
但是,AR 正在发出弃用警告:
弃用警告:将编码器作为位置参数传递已被弃用,并将在 Rails 7.2 中删除。 请将编码器作为关键字参数传递:
序列化:收费,编码器:Byr::Charge
但是当我这样做时,AR 无法将该属性反序列化为费用,而只是将其作为字符串从数据库返回。
class Entry < ActiveRecord::Base
serialize :charge, coder: Charge
end
ent = Entry.find(1)
ent.charge.class => String
我错过了什么,还是其他人看到了这个?
为了确保序列化属性
charge
属于Charge
类,您需要在序列化器调用中指定:type
参数。
方法签名的更改允许您定义单独的编码器和类型类。这样,您的代码可以加载/转储某个类,并使属性属于不同的类。
class Entry < ActiveRecord::Base
serialize :charge, coder: Charge, type: Charge
end
欲了解更多信息,请参阅: