【发布时间】:2017-02-21 20:19:19
【问题描述】:
我正在生成要存储在 rails 中的数据。我已将数据导出为序列化的 JSON 字符串。
如何从这个字符串自动构建一个新对象及其子关联? Model.new(json_string) 引发错误,因为子项是哈希值且未初始化。是循环遍历每个对象并初始化子对象的唯一选择吗?我觉得这里可能有一些我不知道的魔法。
例子:
Child belongs_to :parent
Parent has_many :children
json_string = "{
attribute1:"foo",
attribute2:"bar",
children: [
{attribute1:"foo"},
{attribute1:"foo"}
]}"
Parent.new(json_string)
ActiveRecord::AssociationTypeMismatch: Child(#79652130) expected, got Hash(#69570820)
有没有办法从我的序列化对象中自动初始化新的孩子?真正的问题包括三个子级别。
【问题讨论】:
标签: ruby-on-rails activerecord serialization