您的位置:首页 > 编程语言 > Ruby

Ruby on Rails学习 笔记(一)

2008-01-21 15:51 423 查看
1验证输入的内容是否为空,不能为空 在models
validates_presence_of :title,:description,:image_url
2验证输入的内容为数字型
validates_numericality_of:price
3验证输入的数据price不小于 0.01
protected
def validate
errors.add(:price,"should be at least 0.01") if price.nil?||price<0.01
end
4验证某个字段,在数据库中不允许重复
validates_uniqueness_of:title
5验证图片的 url连接
validates_format_of :image_url,

:with=>%r{\.(gif|jpg|png)$}i,

:message=>"must be a url for a gif,jpg,png image"
6调整样式表
在app/views/layouts目录的html.erb文件中找到样式表行 ,改为
<%= stylesheet_link_tag 'scaffold','depot' %>
7一个 datagrid
<% for product in @products %>
<tr valign="top" class="<%= cycle('list-line-odd', 'list-line-even') %>">行样式交替
<td>
<img class="list-image" src="<%= product.image_url %>"/>
</td>
<td width="60%">
<span class="list-title"><%= h(product.title) %></span><br />h()将html转换,2.0貌似不好用了
<%= h(truncate(product.description, 80)) %>truncate()截取字符串,2.0好像不是80个了
</td>
<td class="list-actions">
<%= link_to 'Show', :action => 'show', :id => product %><br/>
<%= link_to 'Edit', :action => 'edit', :id => product %><br/>
<%= link_to 'Destroy', { :action => 'destroy', :id => product },
:confirm => "Are you sure?",增加了,确认删除对话框
:method => :post %>删除后的,需要刷新页面
</td>
</tr>
<% end %>
8在控制器中增加一个 一个参数的获取
def index调用一个控制器时,若没有明确指定哪个action默认找index
@products=Product.find_products_find_for_sale该参数自动找Models的find_products_find_for_sale方法,获取值
end
9在Models中声明一个类方法
def self.find_product_for_saleself.声明类方法,可通过使用Product.调用,不限制控制器
find(:all,:order => "title")
end
10app/views/layouts目录的html.erb文件为改页面指定所用的css文件
app/views/layouts目录的.rhtml为 模板文件,提供一个布局模板
11添加一个模板文件 rhtml
<div id="banner">
<%= image_tag("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">
<%= yield :layout %>页面的实际内容,显示在这个位置
</div>
</div>
12将货币国际化输出
<span class="price"><%= number_to_currency(product.price) %></span>number_to_currency()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: