Finished chapter 11
[depot.git] / app / controllers / store_controller.rb
1 class StoreController < ApplicationController
2 before_filter :find_cart, :except => :empty_cart
3
4 def index
5 @products = Product.find_products_for_sale
6 # @cart = find_cart
7 end
8
9 def add_to_cart
10 product = Product.find(params[:id])
11 # @cart = find_cart
12 @current_item = @cart.add_product(product)
13 respond_to do |format|
14 format.js if request.xhr?
15 format.html {redirect_to_index}
16 end
17 rescue ActiveRecord::RecordNotFound
18 logger.error("Attempt to access invalid product #{params[:id]}" )
19 redirect_to_index('Invalid product')
20 end
21
22 def empty_cart
23 session[:cart] = nil
24 redirect_to_index unless request.xhr?
25 end
26
27 def checkout
28 # @cart = find_cart
29 if @cart.items.empty?
30 redirect_to_index("Your cart is empty" )
31 else
32 @order = Order.new
33 @during_checkout = true
34 respond_to do |format|
35 format.js if request.xhr?
36 format.html
37 end
38 end
39 end
40
41 def save_order
42 # @cart = find_cart
43 @order = Order.new(params[:order])
44 # @order.add_line_items_from_cart(@cart)
45 @cart.items.each do |item|
46 li = LineItem.new
47 li.product = item.product
48 li.quantity = item.quantity
49 li.total_price = item.price
50 @order.line_items << li
51 end
52 if @order.save
53 session[:cart] = nil
54 redirect_to_index("Thank you for your order")
55 else
56 render :action => 'checkout'
57 end
58 @during_checkout = false
59 end
60
61
62 protected
63
64 # No authorization needed for the store
65 def authorize
66 end
67
68 private
69
70 def find_cart
71 @cart = (session[:cart] ||= Cart.new)
72 end
73
74 def redirect_to_index(msg = nil)
75 flash[:notice] = msg if msg
76 redirect_to :action => 'index'
77 end
78
79 end