Class: CartController

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

Instance Attribute Summary

Attributes inherited from ApplicationController

#req, #res

Instance Method Summary collapse

Methods inherited from ApplicationController

#boolean_param, #csrf_token, #delete_all_images_from_content, #delete_from_storage, #initialize, #params, #redirect_to, #render, #session, #validate!

Constructor Details

This class inherits a constructor from ApplicationController

Instance Method Details

#addObject



12
13
14
15
16
17
18
19
20
21
22
# File 'app/controllers/cart_controller.rb', line 12

def add
  product_id = params['product_id']
  qty = params['qty'].to_i
  qty = 1 if qty <= 0
  
  cart = session['cart'] || {}
  cart[product_id] = (cart[product_id].to_i + qty)
  session['cart'] = cart
  
  redirect_to '/cart'
end

#clearObject



48
49
50
51
# File 'app/controllers/cart_controller.rb', line 48

def clear
  session['cart'] = {}
  redirect_to '/cart'
end

#indexObject



4
5
6
7
8
9
10
# File 'app/controllers/cart_controller.rb', line 4

def index
  @cart_items = session['cart'] || {}
  # Convert string keys to integers for the query
  @products = Product.where(id: @cart_items.keys.map(&:to_i)).all
  @total = @products.sum { |p| p.price * @cart_items[p.id.to_s].to_i }
  render 'cart_index', title: "Your Cart - One-For-All"
end

#removeObject



24
25
26
27
28
29
30
31
# File 'app/controllers/cart_controller.rb', line 24

def remove
  product_id = params['product_id']
  cart = session['cart'] || {}
  cart.delete(product_id)
  session['cart'] = cart
  
  redirect_to '/cart'
end

#updateObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/controllers/cart_controller.rb', line 33

def update
  product_id = params['product_id']
  qty = params['qty'].to_i
  
  cart = session['cart'] || {}
  if qty <= 0
    cart.delete(product_id)
  else
    cart[product_id] = qty
  end
  session['cart'] = cart
  
  redirect_to '/cart'
end