Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.2 iterate through an array

I have an array that looks like this:

@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"}
]

I want to end up being able to do something like this

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

I'm getting the following error

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

The array is not quite in the right format to do this. I need to find a way to be able to iterate through the key/values and extract the attributes so I can call the method I created in the model. Any ideas?

like image 838
ctilley79 Avatar asked Dec 27 '22 22:12

ctilley79


1 Answers

Check following code.

   @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
like image 104
Shamith c Avatar answered Jan 17 '23 12:01

Shamith c