2015-07-04 62 views
0

的瘋狂3.0的現有數量:我希望能夠輕鬆確定產品是否具有特定選項值的庫存(在我的案例中,例如:'medium 「)。我已經能夠一起破解一些東西,但是這看起來真的很笨重,如果沒有已經存在的方法來獲取這些信息,我會非常驚訝。這是代碼我已經能夠拿出來對各種選項值手信息(大小)創建計數的散列是否有現成的方法來確定瘋狂變種

count_hash_by_option_value_name = {} 
    count_hash_by_option_value_id = {} 
    stock_items = product.stock_items 
    stock_items.each do |stock_item| 
    if stock_item.variant.is_master 
     puts "must be the master: #{stock_item.variant.option_values.inspect}" 
    else 
     count_hash_by_option_value_name[stock_item.variant.option_values.first.name] = stock_item.count_on_hand 
     count_hash_by_option_value_id[stock_item.variant.option_values.first.id] = stock_item.count_on_hand 
    end 

    end 

這給了我尺寸名稱的哈希值,並就手值算該產品

{"small"=>1, "medium"=>2, "large"=>0, "x-large"=>4} 

回答

0

同樣的事情也可能滿足你的需求:

product = Spree::Product.find_by!(slug: 'ruby-on-rails-baseball-jersey') 
Hash[product.variants.includes(option_values: :option_type).map { |v| [v.options_text, v.total_on_hand] }] 

在施普雷沙箱這將返回:

{ 
    "Size: S, Color: Red"=>10, 
    "Size: S, Color: Blue"=>10, 
    "Size: S, Color: Green"=>10, 
    "Size: M, Color: Red"=>10, 
    "Size: M, Color: Blue"=>10, 
    "Size: M, Color: Green"=>10, 
    "Size: L, Color: Red"=>10, 
    "Size: L, Color: Blue"=>10, 
    "Size: L, Color: Green"=>10, 
    "Size: XL, Color: Green"=>10 
}