对于狂欢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 :(得分: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] }]
在Spree沙盒中,它返回:
{
"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
}