2011-11-13 8 views
0

私はJSONオブジェクトを投稿すると、代表モデルレコードを作成する小さなAPIを構築しました。データは次のようになります。Railsで深くネストされたオブジェクトを作成する

{ 
    "customer": { 
    "email": "[email protected]", 
    "first_name": "Michael T. Smith", 
    "last_name": "", 
    "shipping_address_1": "", 
    "telephone": "5551211212", 
    "source": "Purchase" 
    }, 
    "order": { 
    "system_order_id": "1070", 
    "shipping_address_1": "", 
    "billing_address_1": "123 Your Street", 
    "shipping": "0", 
    "tax": "0", 
    "total": "299", 
    "invoice_date": 1321157461, 
    "status": "PROCESSING", 
    "additional_specs": "This is my info!", 
    "line_items": [ 
     { 
     "quantity": "1", 
     "price": "239", 
     "product": "Thing A", 
     "comments": "comments" 
     "specification": { 
      "width": "12", 
      "length": "12", 
     }, 
     }, 
     { 
     "quantity": "1", 
     "price": "239", 
     "product": "Thing A", 
     "comments": "comments" 
     "specification": { 
      "width": "12", 
      "length": "12", 
     }, 
     }, 
    ] 
    } 
} 

質問はネストされたオブジェクトを作成する方法です。私のモデルのような設定です:

class Order < ActiveRecord::Base 
    has_many :line_items 
    belongs_to :customer 

    accepts_nested_attributes_for :line_items 
end 

class LineItem < ActiveRecord::Base 
    belongs_to :order 
    has_many :specifications 
end 

class Specification < ActiveRecord::Base 
    belongs_to :LineItem 
end 

私はこのコードを使用してレコードを作成しようとしている:

@order = @customer.orders.build(@data[:order]) 
@order.save 

はこれを行うには良い方法はありますか?現在、私はこのエラーが発生しています:ActiveRecord::AssociationTypeMismatch in ApiController#purchase_request LineItem(#70310607516240) expected, got Hash(#70310854628220)

ありがとう!

答えて

1

accepts_nested_attributes_forは、関連付けのための新しいセッターメソッドを定義しています。元の名前には、_attributesが追加されています。

Orderモデルには、line_items_attributes=メソッドがあります。これは、ネストされた属性機能を利用するために必要なものです。モデルを構築する前にキーを交換するだけの簡単な方法があります。例:

@data[:order][:line_items_attributes] = @data[:order].delete(:line_items) 
@order = @customer.orders.build(@data[:order]) 
@order.save 
関連する問題