在上一篇隨筆中,我們為Products創建了一個維護用的列表頁面,效果如圖:

這次我們使用上面維護的Products列表來創建一個最終用戶使用的購物頁面。
1.創建控制器(Controller),命名為store,我們通過命令行來創建它:
depot> ruby script/generate controller Store index
打開...rails_apps\depot\app\controllers目錄下的store_controller.rb文件,向其中添加代碼:
def index @products = Product.salable_items end
當然,我們還需要給Product定義salable_items方法,打開rails_apps\depot\app\models目錄下的product.rb文件,添加代碼:
def self.salable_items find(:all, :conditions => "date_available <= now()", :order => "date_available desc") end
2.創建表示層,在rails_apps\depot\app\views\store目錄下,創建一個index.rhtml文件,修改其內容如下:
<html>
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag "depot", :media => "all" %>
</head>
<body>
<div id="banner">
<img src="http://images.cnblogs.com/logo.png"/> ||
<%= @page_title || "Pragmatic Bookshelf" %>
</div>
<div id="columns">
<div id="side">
<a href="http://www....">Home</a><br />
<a href="http://www..../faq">Questions</a><br />
<a href="http://www..../news">News</a><br />
<a href="http://www..../contact">Contact</a><br />
</div>
<div id="main">
<%= @content_for_layout %>
<% for product in @products -%>
<div class="catalogentry">
<img src="<%= product.image_url %>"/>
<h3><%= h(product.title) %></h3>
<%= product.description %>
<span class="catalogprice"><%= sprintf("$%0.2f", product.price) %></span>
<%= link_to 'Add to Cart',
{:action => 'add_to_cart', :id => product },
:class => 'addtocart' %><br/>
</div>
<div class="separator"> </div>
<% end %>
<%= link_to "Show my cart", :action => "display_cart" %>
</div>
</div>
</body>
</html>
可以看到,在index.rhtml中,使用了css樣式,css樣式的文件名字叫depot
<%= stylesheet_link_tag "depot", :media => "all" %>
我們可以在rails_apps\depot\public\stylesheets目錄下創建一個depot.css文件來定義我們的樣式。
好了,最終的表示結果應該是這樣:

這時,可以看到畫面上有一個AddCart鏈接,下一篇我們在此基礎上添加一個購物車(cart)應用。