Ruby on Rails学习 笔记(一)

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_sale self.声明类方法,可通过使用Product.调用,不限制控制器
find(:all,:order => "title")
end
10 app/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()
posted on 2008-01-21 15:51  天上  阅读(399)  评论(0编辑  收藏  举报