2017-02-21 11 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) 

自動的に私のシリアライズされたオブジェクトから新しい子を初期化する方法はありますか?実際の問題には、3つの子レベルが含まれます。

答えて

2

children=を使用すると、モデルインスタンスの配列が必要であり、ハッシュから関連するレコードを作成するために使用されることはありません。

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

Parent.new(JSON.parse(json_string)) 
children_attributesとして属性を渡すことで

class Parent 
    has_many :children 
    accepts_nested_attributes_for :children 
end 

これは、あなたが子供を作成できます:

代わりnested attributesを使用

関連する問題