ruby - Rails 3.2 遍历数组

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

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

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

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

最佳答案

检查以下代码。

   @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

关于ruby - Rails 3.2 遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11355820/

相关文章:

java - 无法在 Git Bash 上克隆/推送/pull 项目

ruby-on-rails - Ruby on Rails Thin 和 force_ssl,通过 HTTP 的空响应

python - 在 python 3.x 中将不等数组的 dict 转换为 DataFrame 和 .csv

java - 在 arrayList 中搜索对象,然后多次向同一对象添加值

ruby-on-rails-3.1 - Rails 3.1 生产 Assets : big files are cut into pieces

heroku - 如何从 Rails 应用程序提供 S3 文件?

ruby - 从字符串中获取第一行(不处理整个字符串)

ruby - Errno::EPIPE:使用 Net::FTP 的管道损坏

java - 数据存储类?

ruby-on-rails - ActionMailer 无法在本地主机上使用 gmail 或适用于 Rails 3.1.3 的谷歌应用程序