【问题标题】:Rails 3.2 iterate through an arrayRails 3.2 遍历数组
【发布时间】:2012-07-06 12:51:30
【问题描述】:

我有一个如下所示的数组:

@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>)

数组的格式不完全适合执行此操作。我需要找到一种能够遍历键/值并提取属性的方法,这样我就可以调用我在模型中创建的方法。有什么想法吗?

【问题讨论】:

  • adjust_qtys(p[:old_qty_shipped], p[:qty_shipped], p[:product_id]) 有问题吗?
  • 没有。这工作得很好。即使我想将 @shipment_products 数组的值放到屏幕上也会发生这种情况
  • 使用 p['old_qty_shipped'] 代替 p[:old_qty_shipped]
  • @Shamithc:您可以使用带有ActiveSupport::HashWithIndifferentAccess 的符号或字符串,这就是该类的重点。
  • 我猜这是“冷漠”的部分。

标签: ruby arrays ruby-on-rails-3.1 hash iteration


【解决方案1】:

检查以下代码。

   @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

【讨论】:

  • 谢谢,这很容易。
猜你喜欢
  • 2017-03-03
  • 2015-07-10
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
相关资源
最近更新 更多