Agile Web Development with Rails 3nd Edition学习笔记-完成购物车

这一篇,我们来完成我们的购物车的制作吧。
首先,为了客户能够很方便的把购物车中的产品全部清空,我们需要给我们的购物车添加一个“Empty cart”的按钮。
在add_to_cart.html.erb文件最后加入如下代码:
<%= button_to 'Empty cart', :action => 'empty_cart' %>

这里action指向的具体的处理方法还没有实现,所以,我们还需要在store_controller.erb文件中添加这个方法。
具体代码如下:
def empty_cart
session[:cart] = nil
flash[:notice] = "Your cart is currently empty"
redirect_to :action => 'index'
end

好了,现在开启服务,看看我们的清空购物车的按钮好不好用吧。

接下来,我们需要对我们的代码做一些优化。在之前的错误处理和这里为了显示购物车已经清空的信息,我们都使用了flash对象,而且同样的在设置消息内容之后把页面重定向到了index页面。这些代码除了消息内容不同外,其它的完全相同。所以,我们应该为这些代码抽出一个方法来,这个方法可以叫做“redirect_to_index”或者其它你喜欢的名字。这里我们就叫它“redirect_to_index”吧。
这个方法的代码如下:
private
def redirect_to_index(msg)
flash[:notice] = msg
redirect_to :action => 'index'
end


另外,我们需要对add_to_cart页面做一些美化。首先需要修改add_to_cart.html.erb文件来把购物车中的产品摆放整齐,并为用户把所需开销计算出来。
新的add_to_cart.html.erb文件中的代码如下:
<div class="cart-title">Your Cart</div>
<table>
<% for item in @cart.items %>
<tr>
<td><%= item.quantity %>×</td>
<td><%=h item.title %></td>
<td class="item-price"><%= number_to_currency(item.price) %></td>
</tr>
<% end %>
<tr class="total-line">
<td colspan="2">Total</td>
<td class="total-cell"><%= number_to_currency(@cart.total_price) %></td>
</tr>
</table>
<%= button_to "Empty cart" , :action => :empty_cart %>


这段代码中使用了一个叫做total_price的方法,而这个方法我们还没有在Cart类中定义。那么我们现在就去定义它。
def total_price
@items.sum { |item| item.price }
end

还有一些需要定义的CSS样式,详细如下:
.cart-title {
font: 120% bold;
}
.item-price, .total-line {
text-align: right;
}
.total-line .total-cell {
font-weight: bold;
border-top: 1px solid #595 ;
}


好了,我们的购物车到这里就完成了。
启动你的服务,看看我们的成果吧! :)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值