2011-11-13 81 views
0

我已經構建了一個小的API,它在發佈JSON對象時創建代表模型記錄。數據如下所示:在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