2017-02-21 119 views
1

我正在生成要存储在导轨中的数据。我已经将数据导出为序列化的JSON字符串。从JSON初始化Rails模型 - 如何初始化子关联?

如何从这个字符串中自动构建新对象及其子协会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) 

有没有一种方法来自动从我的序列化对象初始化新的孩子吗?真正的问题包括三个子级。

回答

2

使用children=作为设定器不工作为一个具有许多协会预计模型实例的阵列,并且不旨在被用于从一个散列创建相关的记录。通过传递的属性children_attributes

class Parent 
    has_many :children 
    accepts_nested_attributes_for :children 
end 

这将让你生孩子:

json_string = '{ 
    "attribute1":"foo", 
    "attribute2":"bar", 
    "children_attributes": [ 
    { "attribute1":"foo"}, 
    { "attribute1:""foo"} 
    ] 
}' 

Parent.new(JSON.parse(json_string)) 

而是使用nested attributes