2014-02-06 113 views
0

我正在尝试创建电子商务样式网站,并试图从头开始制作购物篮/购物车。由于用户可以在没有登录的情况下将产品添加到虚拟篮子中,我正在通过浏览器中存储的cookie来执行此过程。该cookie使用以下格式:阵列中的每个值*不同阵列中的另一个值

Product.ID|Quantity/Product2.ID|Quantity 

我使用的一些代码,以分割所述阵列并删除“/和|”并留下两个数组。一个包含所有产品ID和另一个包含数量。

我需要一种方法将数组中的每个值与另一个数组中的正确值进行匹配。例如:

array1 = ["1", "4", "7"] # Products ID'S 
array2 = ["1, "2, "1"] # Quantities 

我需要能够做到产品(1)。价格X 1,产品(4)。价格X 2,产品(7)。价格X(1)

At the moment I do @product = Product.find_all_by_id(array1) which does return my products. I then need to do each products price X the quantity. 

有没有更好/更干净的方式做到这一点或任何人都可以帮忙?我不想为预制的购物车/购物篮系统使用宝石/插件。

非常感谢

回答

0

我建议这样做

可以说您的购物车变量在Cookie中有您的购物车价值

basket = "Product1.ID|Quantity/Product2.ID|Quantity" 

将其转换为一个哈希做

Hash[basket.split("/").map{|p| p.split("|")}] 

现在,您将获得包含产品ID为关键和数量值的哈希

products = {"Product1.ID" => "Quantity", "Product2.ID" => "Quantity"} 

products.each do |product_id, quantity| 
    cost = Product.find(product_id).price * quantity.to_i 
end 
+0

这是真的不错,除了说筐= “3 | 1/4 | 1/3 | 2”所以有三个条目。如果我运行convert to has命令,它只会返回{“3”=>“2”,“4”=>“1”} - 两个条目的顺序相反?有什么想法吗。再次感谢! –

+0

这是因为您有两次相同的产品ID。哈希不能有重复的键。你的情况是否可能? – usha

+0

我明白了!不 - 我需要添加一些不允许重复产品ID的代码。相反,它只会更新数量。谢谢!如果数量重复会发生什么?假设我们有“5 | 2/4 | 1/3 | 2” - 是否会产生错误? –

0

下面将让您遍历第一指数和第二获取匹配的值:

array1.each_with_index do |id, index| 
    product = Product.find(id) 
    cost = product.price * array2[index].to_i 
    # Do something with the cost 
end