Ruby on Rails創建購物頁面技巧一點通
Ruby on Rails是一款性能不錯的WEB開發框架。許多編程人員都靠這個開發框架來實現簡約編程。在這里我們將會為大家詳細介紹有關Ruby on Rails創建購物頁面的一些技巧。#t#
這次我們使用上面維護的Products列表來創建一個最終用戶使用的購物頁面。
1.創建控制器(Controller),命名為store,我們通過命令行來創建它:
depot> ruby script/generate controller Store index
打開...rails_appsdepotappcontrollers目錄下的store_controller.rb文件,向其中添加Ruby on Rails創建購物頁面的代碼:
- def index
- @products =
Product.salable_items- end
當然,我們還需要給Product定義salable_items方法,打開rails_appsdepotappmodels目錄下的product.rb文件,添加代碼:
- def self.salable_items
- find(:all,
- :conditions =>
"date_available < = now()",- :order => "date_available desc")
- end
2.創建表示層,在rails_appsdepotappviewsstore目錄下,創建一個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_appsdepotpublicstylesheets目錄下創建一個depot.css文件來定義我們的樣式以完成Ruby on Rails創建購物頁面的操作。