2012-07-06 73 views
4

我有一個數組,看起來像這樣:的Rails 3.2迭代通過陣列

@shipment_products 
[ 
    {"old_qty_shipped"=>"324", "product_id"=>"1", "qty_shipped"=>"12443"} 
    {"old_qty_shipped"=>"4343423", "product_id"=>"3", "qty_shipped"=>"321344"} 
    {"old_qty_shipped"=>"23", "product_id"=>"4", "qty_shipped"=>"321"} 
] 

我希望最終能夠做這樣的事

@shipment_products.each do |p| 
    Product.adjust_qtys(p.old_qty_shipped, p.qty_shipped, p.product_id) 
end 

我得到以下錯誤

NoMethodError (undefined method `qty_shipped' for #<ActiveSupport::HashWithIndifferentAccess:0x007f>) 

該數組的格式不正確。我需要找到一種方法來遍歷鍵/值並提取屬性,以便我可以調用我在模型中創建的方法。有任何想法嗎?

+1

'adjust_qtys(p [:old_qty_shipped],p [:qty_shipped],p [:product_id])''有什麼問題嗎? – 2012-07-06 04:43:27

+0

沒有。這工作得很好。即使我想將@shipment_products數組的值放到屏幕上,也會發生這種情況 – ctilley79 2012-07-06 04:56:30

+0

使用p ['old_qty_shipped']而不是p [:old_qty_shipped] – 2012-07-06 04:57:42

回答

8

檢查下面的代碼。

@shipment_products = [ {"old_qty_shipped"=>"324", "product_id"=>"1", "qty_shipped"=>"12443"}, {"old_qty_shipped"=>"4343423", "product_id"=>"3", "qty_shipped"=>"321344"} , {"old_qty_shipped"=>"23", "product_id"=>"4", "qty_shipped"=>"321"}] 

    @shipment_products.each do |p| 
     Product.adjust_qtys(p['old_qty_shipped'], p['qty_shipped'], p['product_id']) 
    end 
+0

謝謝,這很容易。 – ctilley79 2012-07-06 05:00:07