You??™ll do that by changing the
layout slightly, by adding this to app/views/layouts/store.rhtml:
<% unless @cart.blank?%>
You have <%=pluralize @cart.length, 'item'%> in your
CHAPTER 5 ?– A DATABASE-DRIVEN SHOP 80
cart for <%= money @price %>.
<%= link_to "Cart",:action=>'cart'%>
<%= button_to 'Empty cart', :action=>'empty_cart',
:back_to=>url_for(params)%>
<% else %>
Your cart is empty
<% end %>
Here you check if there is any cart, and if there is you pluralize the word item, based on
the length of the cart, and also display the current price. You have a link to viewing the contents
of the cart, where checkout will be possible. Last, you also have a button to empty the
cart. Notice the way the url_for helper is used to create a complete URL for getting back to
the current point after emptying the cart. If there??™s no content in the cart, you just write a
small message about this.
Viewing the Cart
The first step toward being able to buy things is to see what you have in your cart. In the last
section you added a link to an action called cart. This action doesn??™t exist yet, but you??™ll add it
to app/controllers/store_controller.rb now:
def cart
menu
@pcart = canon_cart.map {|k,v| [Product.find(k),v] }
end
This method relies heavily on the canon_cart method, which you should add next:
def canon_cart
rcart = Hash.new(0)
c = session[:cart]
unless c.blank?
c.each do |v|
rcart[v] += 1
end
end
rcart
end
The method first creates a new hash, but it does this through the regular constructor.
Pages:
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160