End chapter 8
[depot.git] / app / controllers / store_controller.rb
index 9973d078727c334fc06a948e5bfe6c7a86ff0a56..f0103268556578461452c8c2bfa7b834c71600eb 100644 (file)
@@ -3,4 +3,29 @@ class StoreController < ApplicationController
     @products = Product.find_products_for_sale
   end
 
+  def add_to_cart
+    product = Product.find(params[:id])
+    @cart = find_cart
+    @cart.add_product(product)
+  rescue ActiveRecord::RecordNotFound
+    logger.error("Attempt to access invalid product #{params[:id]}" )
+    redirect_to_index('Invalid product')
+  end
+  
+  def empty_cart
+    session[:cart] = nil
+    redirect_to_index('Your cart has been emptied')
+  end
+  
+ private
+  def find_cart
+    session[:cart] ||= Cart.new
+  end
+
+  def redirect_to_index(msg)
+    flash[:notice] = msg
+    redirect_to :action => 'index'
+  end
+  
 end