2017-02-21 167 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