第六章,创建商品维护程序
收获:
1/通过seed.rb文件设置样式表
Product.delete_all
Product.create(:title=> 'Programming Ruby 1.9',
:description =>
%{<p>
Ruby is thefastest growing and most exciting dynamic language out there.Ifyou need to getworking programs delivered fast,you should add Ruby to your
toolbox.
</p>},
:image_url =>'/images/ruby.jpg',
:price =>49.50)
2/样式表的配置:将depot.css文件放在assets/stylesheets文件夹后,在application.css加入以下语句:
* You're free toadd application-wide styles to this file and they'll appear at thetop of the
* compiledfile, but it's generally better to create a new file per stylescope.
*
*=requiredepot.css
3/layout/application.html.erb为整个应用程序创建标准的页面环境.stylesheet_link_tag创建一个HTML<link>b标签,标签会从stylesheets目录中加载样式表。
<head>
<title>PragprogBooks Online Store</title>
<%=stylesheet_link_tag "scaffold" %>
<%=stylesheet_link_tag "depot", :media => "all"%>
<%=javascript_include_tag :defaults %>
<%=csrf_meta_tags %>
</head>
4/Rails内置特性:
>清单的行背景颜色交替变换:cycle帮助函数通过将每行的CSS类设置为list_even或list_line_odd,并在两个连续行之间自动切换样式名称。
>truncate用来显示描述字段的前80个字符,在调用truncate之前,要调用strip_tags去除字段中的HTML标签
>单击这个链接时会让浏览器弹出一个对话框,要求确认删除该商品
<table>
<%@products.each do |product|%>
<tr class="<%= cycle('list_line_odd','list_line_even')%>">
<td>
<%=image_tag(product.image_url, :class => 'list_image')%>
</td>
<td class="list_description">
<dl>
<dt><%=product.title%></dt>
<dd><%=truncate(strip_tags(product.description),
:length =>80)%></dd>
</dl>
</td>
<td class="list_actions">
<%=link_to 'show',product%><br/>
<%=link_to 'Edit',edit_product_path(product)%><br/>
<%=link_to 'Destroy',product,
:confirm => 'Are you sure?',
:method => :delete%>
</td>
</tr>
<%end%>
</table>
5/回滚迁移:$rakedb:rollback
模式会变回以前的样子,对应表会消失。再次调用rakedb:migrate将重新创建它。
6/验证(在写入数据库之前对其进行检查,使得数据库不会因数据二损坏)
app/models/products.rb中添加以下代码:
validates :title,:description, :image_url, :presence =>true
#validates是标准的Rails验证器,根据一个或多个条件来验证一个或多个模型字段。
#presence=>true让验证器核实每个已命名的字段都存在,且内容不为空
validates :price,:numericality => {:greater_than_or_equal_to =>0.01}
#验证价格是一个有效的正数,数据库只存储小数点后的两位数字,所以传参为0.01
validates:image_url, :format => {
:with =>%r{\.(gif|jpg|png)$}i,
:message =>'must be a URL for GIF,JPG or PNG image.'
}
#\表示全匹配,$表结束符,.表示匹配点
本文介绍如何使用Rails创建商品管理程序,包括通过seed.rb文件设置样式表、布局配置、内置特性如列表交替颜色及字段截断等。同时,还讲解了如何进行数据验证确保数据完整性。
251

被折叠的 条评论
为什么被折叠?



