2012-02-21 76 views
0

我真的很想弄清楚如何遍历一些数据,然后'做'的东西,然后再移动到下一个记录。Rails3新手试图选择和迭代通过阵列

在下面的数组中,我需要提取'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 

回答

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 
+0

认为工作。发生错误时有什么方法可以跳过。例如,如果batch_id = 1在远程查询中不存在? – simonmorley 2012-02-21 12:10:59

+1

几乎可以肯定。我们在谈论什么样的错误?我不知道'Spree.get'做了什么或返回。 – Chowlett 2012-02-21 12:14:08

+0

它不应该通过一个错误,但以防万一。 Spree.get是对我们其他应用程序的httparty调用。它基本上是用batch_id = x来搜索优惠券代码。例如,如果在另一端没有找到id = x的批处理。 – simonmorley 2012-02-21 13:43:02