【ror学习笔记3】页面布局

1.ruby script/generate controller store index   创建控制器Store,其中包含action方法index,当调用一个控制器,又没有明确指定action,会默认调用index

2.编辑app/controllers/store_controller.rb,向模型类Product请求数据库表products

class StoreController < ApplicationController
def index
@products
= Product.find_products_for_sale
end
end

编辑app/models/product.rb,添加find_products_for_sale方法

class Product < ActiveRecord::Base
validates_presence_of
:title,:description,:image_url
validates_numericality_of
:price
validates_uniqueness_of
:title
validates_format_of
:image_url,
:with =>%r{\.(gif|jpg|png)$}i,
:message =>"must be a URL for a GIF,JPG, or PNG image"
protected
def validate
errors
.add(:price,"should be at least 0.01") if price.nil?||price<0.01
end

def self
.find_products_for_sale
find(
:all,:order=>"title")
end
end

3.编辑app/views/store/index.rhtml,编写视图模板

<h1>Your Pragmatic Catalog</h1>
<%for product in @products -%>
<div class="entry">
<img src="<%=product.image_url %>"/>
<h3><%= h(product.title)%><h3>
<%=product.description%>
<div class="price"><%=number_to_currency(product.price)%></div>
<%= button_to "Add to Cart",:action=>:add_to_cart,:id=>product%>
</div>
<%end%>

4.创建app/views/layout/store.rhtml,添加页面布局,如果在app/views/layout目录中创建了一个与某个控制器同名的模板文件,那么该控制器所渲染飞视图默认会使用此布局模板

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Pragprog Books Online Store</title>
<%= stylesheet_link_tag 'depot' ,:media=>"all"%>
</head>
<body id="store">
<div id="banner">
<img src="/images/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">Question</a><br/>
<a href="http://www..../news">News</a><br/>
<a href="http://www..../contact">Contact</a><br/>
</div>
<div id="main">
<%= yield:layout%>
</div>
</div>
</body>
</html>

 

posted on 2010-11-01 21:36  张小捷  阅读(212)  评论(0编辑  收藏  举报

导航