End chapter 10
[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 def checkout
26 @cart = find_cart
27 if @cart.items.empty?
28 redirect_to_index("Your cart is empty" )
29 else
30 @order = Order.new
31 respond_to do |format|
32 format.js if request.xhr?
33 format.html
34 end
35 end
36 end
37
38 def save_order
39 @cart = find_cart
40 @order = Order.new(params[:order])
41 @order.add_line_items_from_cart(@cart)
42 if @order.save
43 session[:cart] = nil
44 redirect_to_index("Thank you for your order")
45 else
46 render :action => 'checkout'
47 end
48 end
49
50
51 private
52
53 def find_cart
54 session[:cart] ||= Cart.new
55 end
56
57 def redirect_to_index(msg = nil)
58 flash[:notice] = msg if msg
59 redirect_to :action => 'index'
60 end
61
62 end