Davey
Davey

Reputation: 1093

Adding and Accessing Multiple Session Variables in Rails

I need a way to change the status of products in my store to sold once a purchase is completed...

I use the following code:

if @order.purchase      #I use active merchant's purchase method on compiled order
  update_product_status #method explained below
end

Before a product is copied as a line_item this code is run:

@product = Product.find(params[:product_id]) #line_item belongs to product and cart
session[:pending_purchase] = @product.id     #stores ID number into session 

So that later I can pull the ID, for the update_product_status code:

def update_product_status              #used to update boolean 'sold' status on product
  product = session[:pending_purchase]
  @sold_product = Product.find(product)
  @sold_product.update(:sold = true)   #not sure if this syntax is correct
end

A problem may present itself if someone buys two items. Will the ID in :pending_purchase get over written if a second line_item is created and added to the cart? How would I access both variables and make sure both items now have a 'sold = true' attribute?

Upvotes: 0

Views: 2844

Answers (1)

Bigxiang
Bigxiang

Reputation: 6692

the simplest way is that stores product's id as an array.

@product = Product.find(params[:product_id])
(session[:pending_purchase] ||= []) && (session[:pending_purchase] << @product.id )

and your will find more products when you use it:

   @products = Product.find(session[:pending_purchase])
   @products.each do |p|
     .........
   end

Upvotes: 1

Related Questions