Question

I'm trying to create a e-commerce style site and am attempting to make basket / cart from scratch. As users will be able to add products to a virutal basket without being signed in, I am doing this process via a cookie stored in the browser. The cookie uses the following format:

Product.ID|Quantity/Product2.ID|Quantity

I use some code to split the array and remove the '/ and |' and am left with two arrays. One containing all of the product ID's and the other containing quantities.

I need a way of matching up each value in the array to the correct value in the other array. For example:

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

I need to be able to do Product(1).price X 1, Product(4).price X 2, Product(7).price 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.

Is there a better / cleaner way of doing this or can anyone help? I DO NOT want to use a gem / plugin for a pre-made cart / basket system.

Many thanks

Lee

Was it helpful?

Solution

I would suggest doing this

Lets say your basket variable has your shopping cart value in the cookie

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

Convert it to a hash by doing

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

Now you will get a hash with product id as the key and quantity as value

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

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

OTHER TIPS

The following will allow you to iterate over the first index and get the matching values from the second:

array1.each_with_index do |id, index|
    product = Product.find(id)
    cost = product.price * array2[index].to_i
    # Do something with the cost 
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top