承接後台商品維護功能,本篇建立前台購物首頁,展示可購買商品並提供「加入購物車」連結。
ruby script/generate controller Store index
修改 store_controller.rb 的 index 動作,取得可販售商品:
def index @products = Product.salable_items end
在 product.rb 定義 salable_items 類別方法,篩選上架日期早於現在的商品,按日期倒序:
def self.salable_items find(:all, :conditions => "date_available <= now()", :order => "date_available desc") end
建立 app/views/store/index.rhtml,使用 CSS 排版,包含橫幅、側邊選單、商品列表區。每個商品顯示圖片、標題、描述、價格與「加入購物車」連結:
<%= link_to 'Add to Cart', {:action => 'add_to_cart', :id => product }, :class => 'addtocart' %>
在 public/stylesheets/depot.css 定義樣式。最終首頁效果如下圖,下一篇將實作購物車功能。
