---
title: "Agile Web Development with Rails 3nd Edition学习笔记-完成购物车"
author: "tiny.strimp"
date: "2010-04-26T22:41:50Z"
tags: []
categories: ["编程语言"]
slug: "agile-web-development-with-rails-3nd-edition"
draft: false
lastmod: "2010-04-26T22:41:50Z"
id: 653718
url: "https://seaoflinux.iteye.com/blog/653718"
---

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

```ruby
<%= button_to 'Empty cart', :action => 'empty_cart' %>
```

这里action指向的具体的处理方法还没有实现，所以，我们还需要在store_controller.erb文件中添加这个方法。
具体代码如下：

```ruby
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”吧。
这个方法的代码如下：

```ruby
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文件中的代码如下：

```ruby
<div class="cart-title">Your Cart</div>
<table>
  <% for item in @cart.items %>
    <tr>
      <td><%= item.quantity %>&times;</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类中定义。那么我们现在就去定义它。

```ruby
def total_price
  @items.sum { |item| item.price }
end
```

还有一些需要定义的CSS样式，详细如下：

```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 ;
}
```


好了，我们的购物车到这里就完成了。
启动你的服务，看看我们的成果吧！ :)