· 8 years ago · Feb 21, 2018, 01:26 PM
1//The Display Cart View
2
3<h1>Display Cart</h1>
4<table>
5<%
6for item in @items
7 @product = item.product
8-%>
9<tr>
10 <td><%= item.quantity %> </td>
11 <td><%= h(product.title) %></td>
12 <td><%= item.unit_price %></td>
13 <td><%= item.unit_price * item.quantity %></td>
14</tr>
15<% end -%>
16</table>
17
18//The Cart Class
19
20class Cart
21 attr_reader :items
22 attr_reader :total_price
23
24 def initialize
25 @items = []
26 @total_price = 0.0
27 end
28
29 def add_product(product)
30 @items << LineItem.for_product(product)
31 @total_price += product.price
32 end
33end
34
35
36//The LineItem class
37
38class LineItem < ActiveRecord::Base
39 belongs_to :product
40
41 def self.for_product(product)
42 item = self.new
43 item.quantity = 1
44 item.product = product
45 item.unit_price = product.price
46
47 end
48end
49
50
51//The Store Controller
52
53class StoreController < ApplicationController
54
55 def index
56 @products = Product.find(:all)
57 end
58
59 def add_to_cart
60 product =Product.find(params[:id])
61 @cart = find_cart
62 @cart.add_product(product)
63 redirect_to(:action => 'display_cart')
64 end
65
66 def display_cart
67 @cart = find_cart
68 @items = @cart.items
69 end
70
71 private
72 def find_cart
73 session[:cart] ||= Cart.new
74 end
75
76
77end
78
79
80
81
82//The SQL for the Tables
83
84drop table if exists products;
85create table products(
86 id int not null auto_increment,
87 title varchar(100) not null,
88 description text not null,
89 image_url varchar(200) not null,
90 price decimal(10,2) not null,
91 primary key(id)
92);
93
94drop table if exists line_items;
95create table line_items(
96 id int not null auto_increment,
97 product_id int not null,
98 quantity int not null default 0,
99 unit_price decimal(10,2),
100 constraint fk_items_product foreign key (product_id) references products(id),
101 primary key(id)
102);