现在的位置: 首页 > 综合 > 正文

Ruby on rails开发从头来(windows)(七)-创建在线购物页面

2012年12月18日 ⁄ 综合 ⁄ 共 2399字 ⁄ 字号 评论关闭

上一篇随笔中,我们为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">&nbsp;</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)应用

抱歉!评论已关闭.