Finished chapter 9
[depot.git] / app / controllers / store_controller.rb
1 class StoreController < ApplicationController
2 def index
3 @products = Product.find_products_for_sale
4 @cart = find_cart
5 end
6
7 def add_to_cart
8 product = Product.find(params[:id])
9 @cart = find_cart
10 @current_item = @cart.add_product(product)
11 respond_to do |format|
12 format.js if request.xhr?
13 format.html {redirect_to_index}
14 end
15 rescue ActiveRecord::RecordNotFound
16 logger.error("Attempt to access invalid product #{params[:id]}" )
17 redirect_to_index('Invalid product')
18 end
19
20 def empty_cart
21 session[:cart] = nil
22 redirect_to_index unless request.xhr?
23 end
24
25 private
26
27 def find_cart
28 session[:cart] ||= Cart.new
29 end
30
31 def redirect_to_index(msg = nil)
32 flash[:notice] = msg if msg
33 redirect_to :action => 'index'
34 end
35
36 end