Class: CartController

Inherits:
ApplicationController show all
Defined in:
app/controllers/cart_controller.rb

Instance Method Summary collapse

Instance Method Details

#destroyObject



36
37
38
39
40
# File 'app/controllers/cart_controller.rb', line 36

def destroy
  session[:cart] = nil
  flash[:notice] = "Your cart has been emptied."
  redirect_to :back
end

#indexObject



6
7
8
# File 'app/controllers/cart_controller.rb', line 6

def index
  @cart = find_cart()
end

#updateObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/controllers/cart_controller.rb', line 10

def update
  cart = find_cart()


  if params.key?('quantity_total_update') && params.key?('cart_item')
    # We are updating the total quantity of multiple items in teh cart. This is likely from teh cart page where
    # the user has updated the quantity text fields and clicked 'Update Cart'
    params['cart_item'].each do |item_id, data|
      cart_item = CartItem.find_by_id(item_id)

      if data.key?('quantity')
        cart.set_item_quantity(cart_item.product, data['quantity'].to_i)
      end
    end
    flash[:notice] = "Your cart has been updated."
  else
    # Adding a given number (quanity) of a particular product. Probably an add to cart from the product page
    product = Product.find_by_id(params[:product_id])
    quantity = (params[:quantity] || 1).to_i
    cart.add(product, quantity)
    flash[:notice] = "#{quantity} #{quantity==1 ? 'item' : 'items'} #{quantity == 1 ? 'has' : 'have'} been added to your <a href='/cart'>cart</a>.".html_safe
  end
  
  redirect_to :back
end