Rails3新手试图通过数组选择和迭代

时间:2012-02-21 10:48:03

标签: ruby-on-rails ruby activerecord spree

我真的很难弄清楚如何迭代一些数据,然后在继续下一条记录之前“做”一些事情。

在下面的数组中,我需要提取'batch_id'并在另一个动作中使用此变量。我的查询如下:

 data = item.line_items.map { |li| li.variant.product }

输出:

[#<Spree::Product id: 706676762, name: "60 Minute Internet Voucher", description: "Lorem ipsum dolor sit amet, consectetuer adipiscing...", available_on: "2012-02-12 18:06:08", deleted_at: nil, permalink: "60-minute-prepaid-wifi-internet-voucher", meta_description: "", meta_keywords: "", tax_category_id: 25484906, shipping_category_id: 727197547, created_at: "2012-02-12 18:06:08", updated_at: "2012-02-21 09:16:01", count_on_hand: 9999964, batch_id: 1, is_voucher: true>, #<Spree::Product id: 569012001, name: "Ruby Baseball Jersey", description: "Lorem ipsum dolor sit amet, consectetuer adipiscing...", available_on: "2012-02-12 18:06:08", deleted_at: nil, permalink: "ruby-baseball-jersey", meta_description: "", meta_keywords: "", tax_category_id: 25484906, shipping_category_id: nil, created_at: "2012-02-12 18:06:08", updated_at: "2012-02-20 22:04:04", count_on_hand: 1000, batch_id: 2990, is_voucher: false>]

我需要逐个遍历每个记录,为另一个查询提取批处理ID。然后继续下一个。我认为这样的事情可能会这样做,但我不能完全理解它:

 1.upto(max_loop) do |i|
   batch_id = xxxx
   Spree.get("/api/v1/radcheck/spree_index?batch_id=#{batch_id}")
   ...
 end

1 个答案:

答案 0 :(得分:2)

你可能只想要:

data.each do |prod|
  begin
    Spree.get("/api/v1/radcheck/spree_index?batch_id=#{prod.batch_id}")
  rescue
    Rails.logger.warn("Something went wrong")
  end
end