我正在生成要存储在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)
有没有办法自动从我的序列化对象初始化新的子对象?真正的问题包括三个 child 级别。
最佳答案
使用 children=
不起作用,因为具有许多关联的 setter 需要模型实例数组,并且不打算用于从哈希创建关联记录。
而是使用 nested attributes :
class Parent
has_many :children
accepts_nested_attributes_for :children
end
这将允许您通过将属性作为 children_attributes
传递来创建子项:
json_string = '{
"attribute1":"foo",
"attribute2":"bar",
"children_attributes": [
{ "attribute1":"foo"},
{ "attribute1:""foo"}
]
}'
Parent.new(JSON.parse(json_string))
关于ruby-on-rails - 从 JSON 初始化 Rails 模型 - 如何初始化子关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42377161/