【发布时间】:2016-06-18 14:38:47
【问题描述】:
在我的代码中,我试图从 JSON 动态实例化 ActiveRecord 模型。示例 Json 为:
{"id":10,"name":"XYZ"}
当我尝试从 Ruby 实例化时:
file_name = "json_file.json"
method = "name"
klass = Kernel.const_get(method.classify)
json = File.read(file_name)
instance = klass.new.from_json(json)
但是当创建Name 类型的实例时,它不包括来自JSON 的id 值。它为零,而我希望它是指定的 10。
如果我尝试插入 instance.save!,那么它每次都会创建一个新 ID,这不是我想要的。
可能是什么原因?
【问题讨论】:
标签: ruby json object instantiation