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