So, the
first thing you should do is add that add_to_cart method to the store controller. Open
app/controllers/store_controller.rb and add this method:
def add_to_cart
p = Product.find(params[:id])
(session[:cart] ||= []) << p.id
session[:price] ||= 0
session[:price] += p.price
flash[:notice] = "#{p.name} added to cart"
redirect_to :action => :products, :id=> p.product_type.id
end
So, as you can see, the add_to_cart method first finds the Product specified, then creates
a cart in the session unless it??™s already there. It then adds the product ID to this cart, and does
the same thing with a running total for price. You add a message to the flash and then redirect
to the products action, showing products for the same type as the product you just added,
because that is a reasonable guess at where the customer originated.
At this point the earlier buttons you added make it possible to add contents to the cart,
but there isn??™t any way to see what??™s in it, empty it, or see the running price. So you??™ll add that
functionality to the menu. If you remember, you earlier created a menu method that gets called
to provide the information the menu layout needs. You??™ll change this to incorporate some
needed changes:
def menu
@types = ProductType.find(:all, :order => 'name ASC')
@cart = session[:cart]
@price = session[:price] || 0
end
As you see, you only provide the cart and the price in instance variables. You??™ll also need
a way to empty the cart, so add the action called empty_cart right now:
def empty_cart
session[:cart] = []
session[:price] = 0
redirect_to params[:back_to]
end
Now you just need to provide these operations to the user.
Pages:
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159