2014-02-06 111 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